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
maybe I'm reading this wrong, but if you set the taskName for the user, are you using it to order the outputs somewhere? Not sure I saw in this PR. I think options are... 1) expose actionName to the user. let the user use this property to correlate inputs and outputs 2) internally set actionName and use this to order match inputs and outputs. User has no concept of actionName.
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return entitiesTask; }).collect(Collectors.toList()); }
.setTaskName(String.valueOf(taskNumber.getAndIncrement()));
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Yeah. I will explore the actionName and default to the service returned ordering for now (as discussed in the internal chat).
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return entitiesTask; }).collect(Collectors.toList()); }
.setTaskName(String.valueOf(taskNumber.getAndIncrement()));
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
isContentResponseOnWriteEnabled() should only matters for write related operation?
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations() != null && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getRequestOptions() != null && ((itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())|| itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){ options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
Yes. Updated
private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return piiTask; }).collect(Collectors.toList()); }
return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map(
private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return entitiesTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { AtomicInteger taskNumber = new AtomicInteger(); return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(String.valueOf(taskNumber.getAndIncrement())); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
actually now I see this is repetitive from L203 and L208
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); }
}
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizePiiEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractKeyPhrasesActions() == null) { return null; } return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeLinkedEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { if (actions == null || actions.getAnalyzeSentimentActions() == null) { return null; } return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractSummaryActions() == null) { return null; } return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
I am kind of wondering if we are fine with the list of actions sent to the service to be `[action1, null, action2, null]`. Should we rather consider be constructing the list as `[action1, action2]` rather than sending back the null?
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); }
final EntitiesTask entitiesTask = new EntitiesTask();
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizePiiEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractKeyPhrasesActions() == null) { return null; } return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeLinkedEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { if (actions == null || actions.getAnalyzeSentimentActions() == null) { return null; } return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractSummaryActions() == null) { return null; } return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Oh yeah. Forget I added it
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); }
}
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizePiiEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractKeyPhrasesActions() == null) { return null; } return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeLinkedEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { if (actions == null || actions.getAnalyzeSentimentActions() == null) { return null; } return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractSummaryActions() == null) { return null; } return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
we should not validate the user input from the client side if not required. Isn't it?
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); }
final EntitiesTask entitiesTask = new EntitiesTask();
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizePiiEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractKeyPhrasesActions() == null) { return null; } return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { if (actions == null || actions.getRecognizeLinkedEntitiesActions() == null) { return null; } return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { if (actions == null || actions.getAnalyzeSentimentActions() == null) { return null; } return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { if (actions == null || actions.getExtractSummaryActions() == null) { return null; } return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Give that the `get*Actions` methods return an `Iterable<T>` do we need to use `Stream` here? Instead could we do a simpler `for (T t : Iterable<T>)` with an external tracking `List` to collect the converted values.
private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); }
return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map(
private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
Should `actions` be forced to be non-null? How do the callers into this method handle a `null` return?
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; }
if (actions == null) {
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
That works too. I will update it to be simplified
private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); }
return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map(
private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
we should not validate the user input from the client side if not required. Isn't it?
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; }
if (actions == null) {
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
if user set a Array of (action1, null, action2). it have to intend to do so. Otherwise, there won't be a case that they will done so.
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; }
if (actions == null) {
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { if (actions == null) { return null; } final JobManifestTasks jobManifestTasks = new JobManifestTasks(); if (actions.getRecognizeEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions)); } if (actions.getRecognizePiiEntitiesActions() != null) { jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions)); } if (actions.getExtractKeyPhrasesActions() != null) { jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions)); } if (actions.getRecognizeLinkedEntitiesActions() != null) { jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions)); } if (actions.getAnalyzeSentimentActions() != null) { jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions)); } if (actions.getExtractSummaryActions() != null) { jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions)); } return jobManifestTasks; }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entitiesTask; }).collect(Collectors.toList()); } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))) .setTaskName(action.getActionName()); return piiTask; }).collect(Collectors.toList()); } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled())) .setTaskName(action.getActionName()); return keyPhrasesTask; }).collect(Collectors.toList()); } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return entityLinkingTask; }).collect(Collectors.toList()); } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)) .setTaskName(action.getActionName()); return sentimentAnalysisTask; }).collect(Collectors.toList()); } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { return StreamSupport.stream(actions.getExtractSummaryActions().spliterator(), false).map( action -> { if (action == null) { return null; } final ExtractiveSummarizationTask extractiveSummarizationTask = new ExtractiveSummarizationTask(); extractiveSummarizationTask .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString()))) .setTaskName(action.getActionName()); return extractiveSummarizationTask; }).collect(Collectors.toList()); } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks"; private static final String REGEX_ACTION_ERROR_TARGET = String.format(" ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS); private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) { final List<EntitiesTask> entitiesTasks = new ArrayList<>(); for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) { if (action == null) { entitiesTasks.add(null); } else { entitiesTasks.add( new EntitiesTask() .setTaskName(action.getActionName()) .setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return entitiesTasks; } private List<PiiTask> toPiiTask(TextAnalyticsActions actions) { final List<PiiTask> piiTasks = new ArrayList<>(); for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) { if (action == null) { piiTasks.add(null); } else { piiTasks.add( new PiiTask() .setTaskName(action.getActionName()) .setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())))); } } return piiTasks; } private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) { final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>(); for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) { if (action == null) { keyPhrasesTasks.add(null); } else { keyPhrasesTasks.add( new KeyPhrasesTask() .setTaskName(action.getActionName()) .setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()))); } } return keyPhrasesTasks; } private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) { final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>(); for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) { if (action == null) { entityLinkingTasks.add(null); } else { new EntityLinkingTask() .setTaskName(action.getActionName()) .setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); } } return entityLinkingTasks; } private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) { final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>(); for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) { if (action == null) { sentimentAnalysisTasks.add(null); } else { sentimentAnalysisTasks.add( new SentimentAnalysisTask() .setTaskName(action.getActionName()) .setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT))); } } return sentimentAnalysisTasks; } private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) { final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>(); for (ExtractSummaryAction action : actions.getExtractSummaryActions()) { if (action == null) { extractiveSummarizationTasks.add(null); } else { extractiveSummarizationTasks.add( new ExtractiveSummarizationTask() .setTaskName(action.getActionName()) .setParameters( new ExtractiveSummarizationTaskParameters() .setModelVersion(action.getModelVersion()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setLoggingOptOut(action.isServiceLogsDisabled()) .setSentenceCount(action.getMaxSentenceCount()) .setSortBy(action.getOrderBy() == null ? null : ExtractiveSummarizationTaskParametersSortBy.fromString( action.getOrderBy().toString())))); } } return extractiveSummarizationTasks; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems = tasksStateTasks.getExtractiveSummarizationTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) { for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) { final TasksStateTasksExtractiveSummarizationTasksItem taskItem = extractiveSummarizationTasksItems.get(i); final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); final ExtractiveSummarizationResult results = taskItem.getResults(); if (results != null) { ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractSummaryResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName()); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractSummaryActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) { actionResult = extractSummaryActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, IterableStream.of(extractSummaryActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
probably not a warn log to user, since it can't do anything
public void setDefaultTokenCredential(TokenCredential defaultTokenCredential) { this.defaultTokenCredential = defaultTokenCredential; }
this.defaultTokenCredential = defaultTokenCredential;
public void setDefaultTokenCredential(TokenCredential defaultTokenCredential) { this.defaultTokenCredential = defaultTokenCredential; }
class {}
class {}
how about we move the concating VERSION logic here instead of puting it in the ApplicationId class
protected void configureApplicationId(T builder) { String applicationId = getApplicationId() + this.springIdentifier; consumeApplicationId().accept(builder, applicationId); }
consumeApplicationId().accept(builder, applicationId);
protected void configureApplicationId(T builder) { String applicationId = getApplicationId() + this.springIdentifier; consumeApplicationId().accept(builder, applicationId); }
class AbstractAzureServiceClientBuilderFactory<T> implements AzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureServiceClientBuilderFactory.class); protected abstract T createBuilderInstance(); protected abstract AzureProperties getAzureProperties(); protected abstract List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(T builder); protected abstract void configureProxy(T builder); protected abstract void configureRetry(T builder); protected abstract void configureService(T builder); protected abstract BiConsumer<T, String> consumeApplicationId(); protected abstract BiConsumer<T, Configuration> consumeConfiguration(); protected abstract BiConsumer<T, TokenCredential> consumeDefaultTokenCredential(); protected abstract BiConsumer<T, String> consumeConnectionString(); protected TokenCredential defaultTokenCredential = new DefaultAzureCredentialBuilder().build(); private AzureEnvironment azureEnvironment = AzureEnvironment.AZURE; private String springIdentifier = ""; private ConnectionStringProvider<?> connectionStringProvider; private boolean credentialConfigured = false; /** * <ol> * <li>Create a builder instance.</li> * <li>Configure Azure core level configuration.</li> * <li>Configure service level configuration.</li> * <li>Customize builder.</li> * </ol> * * @return the service client builder */ public T build() { T builder = createBuilderInstance(); configureCore(builder); configureService(builder); customizeBuilder(builder); return builder; } protected void configureCore(T builder) { configureApplicationId(builder); configureAzureEnvironment(builder); configureRetry(builder); configureProxy(builder); configureCredential(builder); configureConnectionString(builder); configureDefaultCredential(builder); } /** * The application id provided to sdk should be a concatenation of customer-application-id and * azure-spring-identifier. * * @param builder the service client builder */ protected void configureAzureEnvironment(T builder) { Configuration configuration = new Configuration(); configuration.put(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, this.azureEnvironment.getActiveDirectoryEndpoint()); consumeConfiguration().accept(builder, configuration); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void configureCredential(T builder) { List<AuthenticationDescriptor<?>> descriptors = getAuthenticationDescriptors(builder); AzureCredentialProvider<?> azureCredentialProvider = resolveAzureCredential(getAzureProperties(), descriptors); if (azureCredentialProvider == null) { LOGGER.warn("No authentication credential configured for class {}.", builder.getClass()); return; } final Consumer consumer = descriptors.stream() .filter(d -> d.azureCredentialType() == azureCredentialProvider.getType()) .map(AuthenticationDescriptor::consumer) .findFirst() .orElseThrow( () -> new IllegalArgumentException("Consumer should not be null")); consumer.accept(azureCredentialProvider); credentialConfigured = true; } protected void configureConnectionString(T builder) { if (this.connectionStringProvider != null && StringUtils.hasText(this.connectionStringProvider.getConnectionString())) { consumeConnectionString().accept(builder, this.connectionStringProvider.getConnectionString()); credentialConfigured = true; } } protected void configureDefaultCredential(T builder) { if (!credentialConfigured) { LOGGER.info("Will configure the default credential for {}.", builder.getClass()); consumeDefaultTokenCredential().accept(builder, this.defaultTokenCredential); } } protected List<AzureServiceClientBuilderCustomizer<T>> getBuilderCustomizers() { return Collections.singletonList(new NoOpAzureServiceClientBuilderCustomizer<>()); } protected void customizeBuilder(T builder) { for (AzureServiceClientBuilderCustomizer<T> customizer : getBuilderCustomizers()) { customizer.customize(builder); } } private AzureCredentialProvider<?> resolveAzureCredential(AzureProperties azureProperties, List<AuthenticationDescriptor<?>> descriptors) { List<AzureCredentialResolver<?>> resolvers = descriptors.stream() .map(AuthenticationDescriptor::azureCredentialResolver) .collect(Collectors.toList()); AzureCredentialResolvers credentialResolvers = new AzureCredentialResolvers(resolvers); return credentialResolvers.resolve(azureProperties); } protected AzureEnvironment getAzureEnvironment() { return azureEnvironment; } public void setAzureEnvironment(AzureEnvironment azureEnvironment) { this.azureEnvironment = azureEnvironment; } private String getApplicationId() { final ClientProperties clientProperties = getAzureProperties().getClient(); return Optional.ofNullable(clientProperties) .map(ClientProperties::getApplicationId) .orElse(""); } public void setSpringIdentifier(String springIdentifier) { if (!StringUtils.hasText(springIdentifier)) { LOGGER.warn("SpringIdentifier is null or empty."); return; } this.springIdentifier = springIdentifier; } public void setDefaultTokenCredential(TokenCredential defaultTokenCredential) { this.defaultTokenCredential = defaultTokenCredential; } public void setConnectionStringProvider(ConnectionStringProvider<?> connectionStringProvider) { this.connectionStringProvider = connectionStringProvider; } }
class AbstractAzureServiceClientBuilderFactory<T> implements AzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureServiceClientBuilderFactory.class); private static final TokenCredential DEFAULT_TOKEN_CREDENTIAL = new DefaultAzureCredentialBuilder().build(); protected abstract T createBuilderInstance(); protected abstract AzureProperties getAzureProperties(); protected abstract List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(T builder); protected abstract void configureProxy(T builder); protected abstract void configureRetry(T builder); protected abstract void configureService(T builder); protected abstract BiConsumer<T, String> consumeApplicationId(); protected abstract BiConsumer<T, Configuration> consumeConfiguration(); protected abstract BiConsumer<T, TokenCredential> consumeDefaultTokenCredential(); protected abstract BiConsumer<T, String> consumeConnectionString(); protected TokenCredential defaultTokenCredential = DEFAULT_TOKEN_CREDENTIAL; private String applicationId; private String springIdentifier; private ConnectionStringProvider<?> connectionStringProvider; private boolean credentialConfigured = false; /** * <ol> * <li>Create a builder instance.</li> * <li>Configure Azure core level configuration.</li> * <li>Configure service level configuration.</li> * <li>Customize builder.</li> * </ol> * * @return the service client builder */ public T build() { T builder = createBuilderInstance(); configureCore(builder); configureService(builder); customizeBuilder(builder); return builder; } protected void configureCore(T builder) { configureApplicationId(builder); configureAzureEnvironment(builder); configureRetry(builder); configureProxy(builder); configureCredential(builder); configureConnectionString(builder); configureDefaultCredential(builder); } /** * The application id provided to sdk should be a concatenation of customer-application-id and * azure-spring-identifier. * * @param builder the service client builder */ protected void configureAzureEnvironment(T builder) { AzureProfileAware.Profile profile = getAzureProperties().getProfile(); Configuration configuration = new Configuration(); configuration.put(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, profile.getEnvironment().getActiveDirectoryEndpoint()); consumeConfiguration().accept(builder, configuration); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void configureCredential(T builder) { List<AuthenticationDescriptor<?>> descriptors = getAuthenticationDescriptors(builder); AzureCredentialProvider<?> azureCredentialProvider = resolveAzureCredential(getAzureProperties(), descriptors); if (azureCredentialProvider == null) { LOGGER.debug("No authentication credential configured for class {}.", builder.getClass().getSimpleName()); return; } final Consumer consumer = descriptors.stream() .filter(d -> d.azureCredentialType() == azureCredentialProvider.getType()) .map(AuthenticationDescriptor::consumer) .findFirst() .orElseThrow( () -> new IllegalArgumentException("Consumer should not be null")); consumer.accept(azureCredentialProvider); credentialConfigured = true; } protected void configureConnectionString(T builder) { if (this.connectionStringProvider != null && StringUtils.hasText(this.connectionStringProvider.getConnectionString())) { consumeConnectionString().accept(builder, this.connectionStringProvider.getConnectionString()); credentialConfigured = true; LOGGER.debug("Connection string configured for class {}.", builder.getClass().getSimpleName()); } else { AzureProperties azureProperties = getAzureProperties(); if (azureProperties instanceof ConnectionStringAware) { String connectionString = ((ConnectionStringAware) azureProperties).getConnectionString(); if (StringUtils.hasText(connectionString)) { consumeConnectionString().accept(builder, connectionString); credentialConfigured = true; LOGGER.debug("Connection string configured for class {}.", builder.getClass().getSimpleName()); } } } } protected void configureDefaultCredential(T builder) { if (!credentialConfigured) { LOGGER.info("Will configure the default credential for {}.", builder.getClass()); consumeDefaultTokenCredential().accept(builder, this.defaultTokenCredential); } } protected List<AzureServiceClientBuilderCustomizer<T>> getBuilderCustomizers() { return Collections.singletonList(new NoOpAzureServiceClientBuilderCustomizer<>()); } protected void customizeBuilder(T builder) { for (AzureServiceClientBuilderCustomizer<T> customizer : getBuilderCustomizers()) { customizer.customize(builder); } } private AzureCredentialProvider<?> resolveAzureCredential(AzureProperties azureProperties, List<AuthenticationDescriptor<?>> descriptors) { List<AzureCredentialResolver<?>> resolvers = descriptors.stream() .map(AuthenticationDescriptor::azureCredentialResolver) .collect(Collectors.toList()); AzureCredentialResolvers credentialResolvers = new AzureCredentialResolvers(resolvers); return credentialResolvers.resolve(azureProperties); } private String getApplicationId() { final ClientAware.Client client = getAzureProperties().getClient(); return Optional.ofNullable(client) .map(ClientAware.Client::getApplicationId) .orElse(""); } public void setSpringIdentifier(String springIdentifier) { if (!StringUtils.hasText(springIdentifier)) { LOGGER.warn("SpringIdentifier is null or empty."); return; } this.springIdentifier = springIdentifier; } public void setDefaultTokenCredential(TokenCredential defaultTokenCredential) { this.defaultTokenCredential = defaultTokenCredential; } public void setConnectionStringProvider(ConnectionStringProvider<?> connectionStringProvider) { this.connectionStringProvider = connectionStringProvider; } }
Correct - that is why OperationType.READ will be used to enforce content response independent of that flag.
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations() != null && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getRequestOptions() != null && ((itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())|| itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){ options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
Refactored the condition slightly to make it more readable
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations() != null && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getRequestOptions() != null && ((itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())|| itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){ options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
ah, I got it, thanks
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations() != null && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getRequestOptions() != null && ((itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())|| itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){ options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
itemBulkOperation.getOperationType() == CosmosItemOperationType.READ)){
private Mono<CosmosBatchResponse> executeBatchRequest(PartitionKeyRangeServerBatchRequest serverRequest) { RequestOptions options = new RequestOptions(); options.setOperationContextAndListenerTuple(operationListener); if (!this.docClientWrapper.isContentResponseOnWriteEnabled() && serverRequest.getOperations().size() > 0) { for (CosmosItemOperation itemOperation : serverRequest.getOperations()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; if (itemBulkOperation.getOperationType() == CosmosItemOperationType.READ || (itemBulkOperation.getRequestOptions() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled() != null && itemBulkOperation.getRequestOptions().isContentResponseOnWriteEnabled().booleanValue())) { options.setContentResponseOnWriteEnabled(true); break; } } } } return this.docClientWrapper.executeBatchRequest( BridgeInternal.getLink(this.container), serverRequest, options, false); }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
class BulkExecutor<TContext> { private final static Logger logger = LoggerFactory.getLogger(BulkExecutor.class); private final static AtomicLong instanceCount = new AtomicLong(0); private final CosmosAsyncContainer container; private final AsyncDocumentClient docClientWrapper; private final String operationContextText; private final OperationContextAndListenerTuple operationListener; private final ThrottlingRetryOptions throttlingRetryOptions; private final Flux<com.azure.cosmos.models.CosmosItemOperation> inputOperations; private final Long maxMicroBatchIntervalInMs; private final TContext batchContext; private final ConcurrentMap<String, PartitionScopeThresholds> partitionScopeThresholds; private final CosmosBulkExecutionOptions cosmosBulkExecutionOptions; private final AtomicBoolean mainSourceCompleted; private final AtomicInteger totalCount; private final FluxProcessor<CosmosItemOperation, CosmosItemOperation> mainFluxProcessor; private final FluxSink<CosmosItemOperation> mainSink; private final List<FluxSink<CosmosItemOperation>> groupSinks; private final ScheduledExecutorService executorService; public BulkExecutor(CosmosAsyncContainer container, Flux<CosmosItemOperation> inputOperations, CosmosBulkExecutionOptions cosmosBulkOptions) { checkNotNull(container, "expected non-null container"); checkNotNull(inputOperations, "expected non-null inputOperations"); checkNotNull(cosmosBulkOptions, "expected non-null bulkOptions"); this.cosmosBulkExecutionOptions = cosmosBulkOptions; this.container = container; this.inputOperations = inputOperations; this.docClientWrapper = CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()); this.throttlingRetryOptions = docClientWrapper.getConnectionPolicy().getThrottlingRetryOptions(); maxMicroBatchIntervalInMs = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchInterval(cosmosBulkExecutionOptions) .toMillis(); batchContext = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getLegacyBatchScopedContext(cosmosBulkExecutionOptions); this.partitionScopeThresholds = ImplementationBridgeHelpers.CosmosBulkExecutionThresholdsStateHelper .getBulkExecutionThresholdsAccessor() .getPartitionScopeThresholds(cosmosBulkExecutionOptions.getThresholdsState()); operationListener = ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getOperationContext(cosmosBulkExecutionOptions); if (operationListener != null && operationListener.getOperationContext() != null) { operationContextText = operationListener.getOperationContext().toString(); } else { operationContextText = "n/a"; } mainSourceCompleted = new AtomicBoolean(false); totalCount = new AtomicInteger(0); mainFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); mainSink = mainFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks = new CopyOnWriteArrayList<>(); this.executorService = Executors.newSingleThreadScheduledExecutor( new CosmosDaemonThreadFactory("BulkExecutor-" + instanceCount.incrementAndGet())); this.executorService.scheduleWithFixedDelay( this::onFlush, this.maxMicroBatchIntervalInMs, this.maxMicroBatchIntervalInMs, TimeUnit.MILLISECONDS); } public Flux<CosmosBulkOperationResponse<TContext>> execute() { return this.inputOperations .onErrorContinue((throwable, o) -> logger.error("Skipping an error operation while processing {}. Cause: {}, Context: {}", o, throwable.getMessage(), this.operationContextText)) .doOnNext((CosmosItemOperation cosmosItemOperation) -> { BulkExecutorUtil.setRetryPolicyForBulk( docClientWrapper, this.container, cosmosItemOperation, this.throttlingRetryOptions); if (cosmosItemOperation != FlushBuffersItemOperation.singleton()) { totalCount.incrementAndGet(); } }) .doOnComplete(() -> { mainSourceCompleted.set(true); long totalCountSnapshot = totalCount.get(); logger.debug("Main source completed - totalCountSnapshot, this.operationContextText); if (totalCountSnapshot == 0) { completeAllSinks(); } else { this.onFlush(); } }) .mergeWith(mainFluxProcessor) .flatMap(operation -> { return BulkExecutorUtil.resolvePartitionKeyRangeId(this.docClientWrapper, this.container, operation) .map((String pkRangeId) -> { PartitionScopeThresholds partitionScopeThresholds = this.partitionScopeThresholds.computeIfAbsent( pkRangeId, (newPkRangeId) -> new PartitionScopeThresholds(newPkRangeId, this.cosmosBulkExecutionOptions)); return Pair.of(partitionScopeThresholds, operation); }); }) .groupBy(Pair::getKey, Pair::getValue) .flatMap(this::executePartitionedGroup) .doOnNext(requestAndResponse -> { int totalCountAfterDecrement = totalCount.decrementAndGet(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountAfterDecrement == 0 && mainSourceCompletedSnapshot) { logger.debug("All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountAfterDecrement, mainSourceCompletedSnapshot, this.operationContextText); } }) .doOnComplete(() -> { int totalCountSnapshot = totalCount.get(); boolean mainSourceCompletedSnapshot = mainSourceCompleted.get(); if (totalCountSnapshot == 0 && mainSourceCompletedSnapshot) { logger.debug("DoOnComplete: All work completed, Context: {}", this.operationContextText); completeAllSinks(); } else { logger.debug( "DoOnComplete: Work left - TotalCount after decrement: {}, main sink completed {}, Context: {}", totalCountSnapshot, mainSourceCompletedSnapshot, this.operationContextText); } }); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionedGroup( GroupedFlux<PartitionScopeThresholds, CosmosItemOperation> partitionedGroupFluxOfInputOperations) { final PartitionScopeThresholds thresholds = partitionedGroupFluxOfInputOperations.key(); final FluxProcessor<CosmosItemOperation, CosmosItemOperation> groupFluxProcessor = UnicastProcessor.<CosmosItemOperation>create().serialize(); final FluxSink<CosmosItemOperation> groupSink = groupFluxProcessor.sink(FluxSink.OverflowStrategy.BUFFER); groupSinks.add(groupSink); AtomicLong firstRecordTimeStamp = new AtomicLong(-1); AtomicLong currentMicroBatchSize = new AtomicLong(0); return partitionedGroupFluxOfInputOperations .mergeWith(groupFluxProcessor) .onBackpressureBuffer() .timestamp() .bufferUntil(timeStampItemOperationTuple -> { long timestamp = timeStampItemOperationTuple.getT1(); CosmosItemOperation itemOperation = timeStampItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { if (currentMicroBatchSize.get() > 0) { logger.debug( "Flushing PKRange {} due to FlushItemOperation, Context: {}", thresholds.getPartitionKeyRangeId(), this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; } firstRecordTimeStamp.compareAndSet(-1, timestamp); long age = timestamp - firstRecordTimeStamp.get(); long batchSize = currentMicroBatchSize.incrementAndGet(); if (batchSize >= thresholds.getTargetMicroBatchSizeSnapshot() || age >= this.maxMicroBatchIntervalInMs) { logger.debug( "Flushing PKRange {} due to BatchSize ({}) or age ({}), Context: {}", thresholds.getPartitionKeyRangeId(), batchSize, age, this.operationContextText); firstRecordTimeStamp.set(-1); currentMicroBatchSize.set(0); return true; } return false; }) .flatMap( (List<Tuple2<Long, CosmosItemOperation>> timeStampAndItemOperationTuples) -> { List<CosmosItemOperation> operations = new ArrayList<>(timeStampAndItemOperationTuples.size()); for (Tuple2<Long, CosmosItemOperation> timeStampAndItemOperationTuple : timeStampAndItemOperationTuples) { CosmosItemOperation itemOperation = timeStampAndItemOperationTuple.getT2(); if (itemOperation == FlushBuffersItemOperation.singleton()) { continue; } operations.add(itemOperation); } return executeOperations(operations, thresholds, groupSink); }, ImplementationBridgeHelpers.CosmosBulkExecutionOptionsHelper .getCosmosBulkExecutionOptionsAccessor() .getMaxMicroBatchConcurrency(this.cosmosBulkExecutionOptions)); } private Flux<CosmosBulkOperationResponse<TContext>> executeOperations( List<CosmosItemOperation> operations, PartitionScopeThresholds thresholds, FluxSink<CosmosItemOperation> groupSink) { if (operations.size() == 0) { logger.debug("Empty operations list, Context: {}", this.operationContextText); return Flux.empty(); } String pkRange = thresholds.getPartitionKeyRangeId(); ServerOperationBatchRequest serverOperationBatchRequest = BulkExecutorUtil.createBatchRequest(operations, pkRange); if (serverOperationBatchRequest.getBatchPendingOperations().size() > 0) { serverOperationBatchRequest.getBatchPendingOperations().forEach(groupSink::next); } return Flux.just(serverOperationBatchRequest.getBatchRequest()) .publishOn(Schedulers.boundedElastic()) .flatMap((PartitionKeyRangeServerBatchRequest serverRequest) -> this.executePartitionKeyRangeServerBatchRequest(serverRequest, groupSink, thresholds)); } private Flux<CosmosBulkOperationResponse<TContext>> executePartitionKeyRangeServerBatchRequest( PartitionKeyRangeServerBatchRequest serverRequest, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { return this.executeBatchRequest(serverRequest) .flatMapMany(response -> Flux.fromIterable(response.getResults()).flatMap((CosmosBatchOperationResult result) -> handleTransactionalBatchOperationResult(response, result, groupSink, thresholds))) .onErrorResume((Throwable throwable) -> { if (!(throwable instanceof Exception)) { throw Exceptions.propagate(throwable); } Exception exception = (Exception) throwable; return Flux.fromIterable(serverRequest.getOperations()).flatMap((CosmosItemOperation itemOperation) -> handleTransactionalBatchExecutionException(itemOperation, exception, groupSink, thresholds)); }); } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchOperationResult( CosmosBatchResponse response, CosmosBatchOperationResult operationResult, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { CosmosBulkItemResponse cosmosBulkItemResponse = ModelBridgeInternal.createCosmosBulkItemResponse(operationResult, response); CosmosItemOperation itemOperation = operationResult.getOperation(); TContext actualContext = this.getActualContext(itemOperation); if (!operationResult.isSuccessStatusCode()) { if (itemOperation instanceof ItemBulkOperation<?, ?>) { ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy().shouldRetry(operationResult).flatMap( result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } }); } else { throw new UnsupportedOperationException("Unknown CosmosItemOperation."); } } thresholds.recordSuccessfulOperation(); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, cosmosBulkItemResponse, actualContext)); } private TContext getActualContext(CosmosItemOperation itemOperation) { ItemBulkOperation<?, ?> itemBulkOperation = null; if (itemOperation instanceof ItemBulkOperation<?, ?>) { itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; } if (itemBulkOperation == null) { return this.batchContext; } TContext operationContext = itemBulkOperation.getContext(); if (operationContext != null) { return operationContext; } return this.batchContext; } private Mono<CosmosBulkOperationResponse<TContext>> handleTransactionalBatchExecutionException( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, PartitionScopeThresholds thresholds) { if (exception instanceof CosmosException && itemOperation instanceof ItemBulkOperation<?, ?>) { CosmosException cosmosException = (CosmosException) exception; ItemBulkOperation<?, ?> itemBulkOperation = (ItemBulkOperation<?, ?>) itemOperation; return itemBulkOperation.getRetryPolicy() .shouldRetryForGone(cosmosException.getStatusCode(), cosmosException.getSubStatusCode()) .flatMap(shouldRetryGone -> { if (shouldRetryGone) { mainSink.next(itemOperation); return Mono.empty(); } else { return retryOtherExceptions( itemOperation, exception, groupSink, cosmosException, itemBulkOperation, thresholds); } }); } TContext actualContext = this.getActualContext(itemOperation); return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse(itemOperation, exception, actualContext)); } private Mono<CosmosBulkOperationResponse<TContext>> enqueueForRetry( Duration backOffTime, FluxSink<CosmosItemOperation> groupSink, CosmosItemOperation itemOperation, PartitionScopeThresholds thresholds) { thresholds.recordEnqueuedRetry(); if (backOffTime == null || backOffTime.isZero()) { groupSink.next(itemOperation); return Mono.empty(); } else { return Mono .delay(backOffTime) .flatMap((dummy) -> { groupSink.next(itemOperation); return Mono.empty(); }); } } private Mono<CosmosBulkOperationResponse<TContext>> retryOtherExceptions( CosmosItemOperation itemOperation, Exception exception, FluxSink<CosmosItemOperation> groupSink, CosmosException cosmosException, ItemBulkOperation<?, ?> itemBulkOperation, PartitionScopeThresholds thresholds) { TContext actualContext = this.getActualContext(itemOperation); return itemBulkOperation.getRetryPolicy().shouldRetry(cosmosException).flatMap(result -> { if (result.shouldRetry) { return this.enqueueForRetry(result.backOffTime, groupSink, itemBulkOperation, thresholds); } else { return Mono.just(ModelBridgeInternal.createCosmosBulkOperationResponse( itemOperation, exception, actualContext)); } }); } private void completeAllSinks() { logger.info("Closing all sinks, Context: {}", this.operationContextText); executorService.shutdown(); logger.debug("Executor service shut down, Context: {}", this.operationContextText); mainSink.complete(); logger.debug("Main sink completed, Context: {}", this.operationContextText); groupSinks.forEach(FluxSink::complete); logger.debug("All group sinks completed, Context: {}", this.operationContextText); } private void onFlush() { try { this.groupSinks.forEach(sink -> sink.next(FlushBuffersItemOperation.singleton())); } catch(Throwable t) { logger.error("Callback invocation 'onFlush' failed.", t); } } }
Ideally `createOrUpdateSiteConfig` should call `updateConfigurationAsync` instead (when in update flow).
Mono<Indexable> submitSiteConfig() { if (siteConfig == null) { return Mono.just((Indexable) this); } if (siteConfig.azureStorageAccounts() != null) { siteConfig.withAzureStorageAccounts( siteConfig.azureStorageAccounts().entrySet().stream() .filter(e -> e.getValue() != null && e.getValue().accessKey() != null) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } return createOrUpdateSiteConfig(siteConfig) .flatMap( returnedSiteConfig -> { siteConfig = returnedSiteConfig; return Mono.just((Indexable) WebAppBaseImpl.this); }); }
return createOrUpdateSiteConfig(siteConfig)
Mono<Indexable> submitSiteConfig() { if (siteConfig == null) { return Mono.just((Indexable) this); } if (siteConfig.azureStorageAccounts() != null) { if (siteConfig.azureStorageAccounts().values().stream() .filter(Objects::nonNull) .anyMatch(v -> v.accessKey() == null)) { siteConfig.withAzureStorageAccounts(null); } } return createOrUpdateSiteConfig(siteConfig) .flatMap( returnedSiteConfig -> { siteConfig = returnedSiteConfig; return Mono.just((Indexable) WebAppBaseImpl.this); }); }
class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>> extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager> implements WebAppBase, WebAppBase.Definition<FluentT>, WebAppBase.Update<FluentT>, WebAppBase.UpdateStages.WithWebContainer<FluentT> { private final ClientLogger logger = new ClientLogger(getClass()); protected static final String SETTING_DOCKER_IMAGE = "DOCKER_CUSTOM_IMAGE_NAME"; protected static final String SETTING_REGISTRY_SERVER = "DOCKER_REGISTRY_SERVER_URL"; protected static final String SETTING_REGISTRY_USERNAME = "DOCKER_REGISTRY_SERVER_USERNAME"; protected static final String SETTING_REGISTRY_PASSWORD = "DOCKER_REGISTRY_SERVER_PASSWORD"; protected static final String SETTING_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; protected static final String SETTING_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; protected static final String IP_RESTRICTION_ACTION_ALLOW = "Allow"; protected static final String IP_RESTRICTION_ACTION_DENY = "Deny"; private static final Map<AzureEnvironment, String> DNS_MAP = new HashMap<AzureEnvironment, String>() { { put(AzureEnvironment.AZURE, "azurewebsites.net"); put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn"); put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de"); put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us"); } }; SiteConfigResourceInner siteConfig; KuduClient kuduClient; WebSiteBase webSiteBase; private Map<String, HostnameSslState> hostNameSslStateMap; private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate; private List<String> hostNameBindingsToDelete; private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate; protected Map<String, String> appSettingsToAdd; protected List<String> appSettingsToRemove; private Map<String, Boolean> appSettingStickiness; private Map<String, ConnStringValueTypePair> connectionStringsToAdd; private List<String> connectionStringsToRemove; private Map<String, Boolean> connectionStringStickiness; private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl; private boolean sourceControlToDelete; private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication; private boolean authenticationToUpdate; private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs; private boolean diagnosticLogsToUpdate; private FunctionalTaskItem msiHandler; private boolean isInCreateMode; private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler; WebAppBaseImpl( String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, manager); if (innerObject != null && innerObject.kind() != null) { innerObject.withKind(innerObject.kind().replace(";", ",")); } this.siteConfig = siteConfig; if (logConfig != null) { this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this); } webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this); normalizeProperties(); isInCreateMode = innerModel() == null || innerModel().id() == null; if (!isInCreateMode) { initializeKuduClient(); } } public boolean isInCreateMode() { return isInCreateMode; } private void initializeKuduClient() { if (kuduClient == null) { kuduClient = new KuduClient(this); } } @Override public void setInner(SiteInner innerObject) { if (innerObject.kind() != null) { innerObject.withKind(innerObject.kind().replace(";", ",")); } super.setInner(innerObject); } RoleAssignmentHelper.IdProvider idProvider() { return new RoleAssignmentHelper.IdProvider() { @Override public String principalId() { if (innerModel() != null && innerModel().identity() != null) { return innerModel().identity().principalId(); } else { return null; } } @Override public String resourceId() { if (innerModel() != null) { return innerModel().id(); } else { return null; } } }; } private void normalizeProperties() { this.hostNameBindingsToCreate = new TreeMap<>(); this.hostNameBindingsToDelete = new ArrayList<>(); this.appSettingsToAdd = new HashMap<>(); this.appSettingsToRemove = new ArrayList<>(); this.appSettingStickiness = new HashMap<>(); this.connectionStringsToAdd = new HashMap<>(); this.connectionStringsToRemove = new ArrayList<>(); this.connectionStringStickiness = new HashMap<>(); this.sourceControl = null; this.sourceControlToDelete = false; this.authenticationToUpdate = false; this.diagnosticLogsToUpdate = false; this.sslBindingsToCreate = new TreeMap<>(); this.msiHandler = null; this.webSiteBase = new WebSiteBaseImpl(innerModel()); this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates()); this.webAppMsiHandler.clear(); } @Override public String state() { return webSiteBase.state(); } @Override public Set<String> hostnames() { return webSiteBase.hostnames(); } @Override public String repositorySiteName() { return webSiteBase.repositorySiteName(); } @Override public UsageState usageState() { return webSiteBase.usageState(); } @Override public boolean enabled() { return webSiteBase.enabled(); } @Override public Set<String> enabledHostNames() { return webSiteBase.enabledHostNames(); } @Override public SiteAvailabilityState availabilityState() { return webSiteBase.availabilityState(); } @Override public Map<String, HostnameSslState> hostnameSslStates() { return Collections.unmodifiableMap(hostNameSslStateMap); } @Override public String appServicePlanId() { return webSiteBase.appServicePlanId(); } @Override public OffsetDateTime lastModifiedTime() { return webSiteBase.lastModifiedTime(); } @Override public Set<String> trafficManagerHostNames() { return webSiteBase.trafficManagerHostNames(); } @Override public boolean scmSiteAlsoStopped() { return webSiteBase.scmSiteAlsoStopped(); } @Override public String targetSwapSlot() { return webSiteBase.targetSwapSlot(); } @Override public boolean clientAffinityEnabled() { return webSiteBase.clientAffinityEnabled(); } @Override public boolean clientCertEnabled() { return webSiteBase.clientCertEnabled(); } @Override public boolean hostnamesDisabled() { return webSiteBase.hostnamesDisabled(); } @Override public Set<String> outboundIPAddresses() { return webSiteBase.outboundIPAddresses(); } @Override public int containerSize() { return webSiteBase.containerSize(); } @Override public CloningInfo cloningInfo() { return webSiteBase.cloningInfo(); } @Override public boolean isDefaultContainer() { return webSiteBase.isDefaultContainer(); } @Override public String defaultHostname() { if (innerModel().defaultHostname() != null) { return innerModel().defaultHostname(); } else { AzureEnvironment environment = manager().environment(); String dns = DNS_MAP.get(environment); String leaf = name(); if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) { leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf; } return leaf + "." + dns; } } @Override public List<String> defaultDocuments() { if (siteConfig == null) { return null; } return Collections.unmodifiableList(siteConfig.defaultDocuments()); } @Override public NetFrameworkVersion netFrameworkVersion() { if (siteConfig == null) { return null; } return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion()); } @Override public PhpVersion phpVersion() { if (siteConfig == null || siteConfig.phpVersion() == null) { return PhpVersion.OFF; } return PhpVersion.fromString(siteConfig.phpVersion()); } @Override public PythonVersion pythonVersion() { if (siteConfig == null || siteConfig.pythonVersion() == null) { return PythonVersion.OFF; } return PythonVersion.fromString(siteConfig.pythonVersion()); } @Override public String nodeVersion() { if (siteConfig == null) { return null; } return siteConfig.nodeVersion(); } @Override public boolean remoteDebuggingEnabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled()); } @Override public RemoteVisualStudioVersion remoteDebuggingVersion() { if (siteConfig == null) { return null; } return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion()); } @Override public boolean webSocketsEnabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.webSocketsEnabled()); } @Override public boolean alwaysOn() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.alwaysOn()); } @Override public JavaVersion javaVersion() { if (siteConfig == null || siteConfig.javaVersion() == null) { return JavaVersion.OFF; } return JavaVersion.fromString(siteConfig.javaVersion()); } @Override public String javaContainer() { if (siteConfig == null) { return null; } return siteConfig.javaContainer(); } @Override public String javaContainerVersion() { if (siteConfig == null) { return null; } return siteConfig.javaContainerVersion(); } @Override public ManagedPipelineMode managedPipelineMode() { if (siteConfig == null) { return null; } return siteConfig.managedPipelineMode(); } @Override public PlatformArchitecture platformArchitecture() { if (siteConfig.use32BitWorkerProcess()) { return PlatformArchitecture.X86; } else { return PlatformArchitecture.X64; } } @Override public String linuxFxVersion() { if (siteConfig == null) { return null; } return siteConfig.linuxFxVersion(); } @Override public String windowsFxVersion() { if (siteConfig == null) { return null; } return siteConfig.windowsFxVersion(); } @Override public String autoSwapSlotName() { if (siteConfig == null) { return null; } return siteConfig.autoSwapSlotName(); } @Override public boolean httpsOnly() { return webSiteBase.httpsOnly(); } @Override public FtpsState ftpsState() { if (siteConfig == null) { return null; } return siteConfig.ftpsState(); } @Override public List<VirtualApplication> virtualApplications() { if (siteConfig == null) { return null; } return siteConfig.virtualApplications(); } @Override public boolean http20Enabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.http20Enabled()); } @Override public boolean localMySqlEnabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.localMySqlEnabled()); } @Override public ScmType scmType() { if (siteConfig == null) { return null; } return siteConfig.scmType(); } @Override public String documentRoot() { if (siteConfig == null) { return null; } return siteConfig.documentRoot(); } @Override public SupportedTlsVersions minTlsVersion() { if (siteConfig == null) { return null; } return siteConfig.minTlsVersion(); } @Override public List<IpSecurityRestriction> ipSecurityRules() { if (this.siteConfig == null || this.siteConfig.ipSecurityRestrictions() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(siteConfig.ipSecurityRestrictions()); } @Override public OperatingSystem operatingSystem() { if (innerModel().kind() != null && innerModel().kind().toLowerCase(Locale.ROOT).contains("linux")) { return OperatingSystem.LINUX; } else { return OperatingSystem.WINDOWS; } } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (innerModel().identity() == null) { return null; } return innerModel().identity().tenantId(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (innerModel().identity() == null) { return null; } return innerModel().identity().principalId(); } @Override public Set<String> userAssignedManagedServiceIdentityIds() { if (innerModel().identity() == null) { return null; } return innerModel().identity().userAssignedIdentities().keySet(); } @Override public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() { return diagnosticLogs; } @Override public InputStream streamApplicationLogs() { return pipeObservableToInputStream(streamApplicationLogsAsync()); } @Override public Flux<String> streamApplicationLogsAsync() { return kuduClient.streamApplicationLogsAsync(); } @Override public InputStream streamHttpLogs() { return pipeObservableToInputStream(streamHttpLogsAsync()); } @Override public Flux<String> streamHttpLogsAsync() { return kuduClient.streamHttpLogsAsync(); } @Override public InputStream streamTraceLogs() { return pipeObservableToInputStream(streamTraceLogsAsync()); } @Override public Flux<String> streamTraceLogsAsync() { return kuduClient.streamTraceLogsAsync(); } @Override public InputStream streamDeploymentLogs() { return pipeObservableToInputStream(streamDeploymentLogsAsync()); } @Override public Flux<String> streamDeploymentLogsAsync() { return kuduClient.streamDeploymentLogsAsync(); } @Override public InputStream streamAllLogs() { return pipeObservableToInputStream(streamAllLogsAsync()); } @Override public Flux<String> streamAllLogsAsync() { return kuduClient.streamAllLogsAsync(); } private InputStream pipeObservableToInputStream(Flux<String> observable) { PipedInputStreamWithCallback in = new PipedInputStreamWithCallback(); final PipedOutputStream out = new PipedOutputStream(); try { in.connect(out); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } final Disposable subscription = observable .subscribeOn(Schedulers.boundedElastic()) .subscribe( s -> { try { out.write(s.getBytes(StandardCharsets.UTF_8)); out.write('\n'); out.flush(); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } }); in .addCallback( () -> { subscription.dispose(); try { out.close(); } catch (IOException e) { e.printStackTrace(); } }); return in; } @Override public Map<String, AppSetting> getAppSettings() { return getAppSettingsAsync().block(); } @Override public Mono<Map<String, AppSetting>> getAppSettingsAsync() { return Mono .zip( listAppSettings(), listSlotConfigurations(), (appSettingsInner, slotConfigs) -> appSettingsInner .properties() .entrySet() .stream() .collect( Collectors .toMap( Map.Entry::getKey, entry -> new AppSettingImpl( entry.getKey(), entry.getValue(), slotConfigs.appSettingNames() != null && slotConfigs.appSettingNames().contains(entry.getKey()))))); } @Override public Map<String, ConnectionString> getConnectionStrings() { return getConnectionStringsAsync().block(); } @Override public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() { return Mono .zip( listConnectionStrings(), listSlotConfigurations(), (connectionStringsInner, slotConfigs) -> connectionStringsInner .properties() .entrySet() .stream() .collect( Collectors .toMap( Map.Entry::getKey, entry -> new ConnectionStringImpl( entry.getKey(), entry.getValue(), slotConfigs.connectionStringNames() != null && slotConfigs.connectionStringNames().contains(entry.getKey()))))); } @Override public WebAppAuthentication getAuthenticationConfig() { return getAuthenticationConfigAsync().block(); } @Override public Mono<WebAppAuthentication> getAuthenticationConfigAsync() { return getAuthentication() .map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this)); } abstract Mono<SiteInner> createOrUpdateInner(SiteInner site); abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate); abstract Mono<SiteInner> getInner(); abstract Mono<SiteConfigResourceInner> getConfigInner(); abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig); abstract Mono<Void> deleteHostnameBinding(String hostname); abstract Mono<StringDictionaryInner> listAppSettings(); abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner); abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings(); abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner); abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations(); abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner); abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner); abstract Mono<Void> deleteSourceControl(); abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner); abstract Mono<SiteAuthSettingsInner> getAuthentication(); abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner); abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner); @Override public void beforeGroupCreateOrUpdate() { if (hostNameSslStateMap.size() > 0) { innerModel().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values())); } IndexableTaskItem rootTaskItem = wrapTask( context -> { return submitHostNameBindings() .flatMap(fluentT -> submitSslBindings(fluentT.innerModel())); }); IndexableTaskItem lastTaskItem = rootTaskItem; lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig()); lastTaskItem = sequentialTask( lastTaskItem, context -> submitMetadata() .flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last()) .flatMap(ignored -> submitStickiness())); lastTaskItem = sequentialTask( lastTaskItem, context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate())); lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication()); lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration()); if (msiHandler != null) { sequentialTask(lastTaskItem, msiHandler); } addPostRunDependent(rootTaskItem); } private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) { return IndexableTaskItem.create(taskItem); } private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) { IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2); taskItem1.addPostRunDependent(taskItem); return taskItem; } @Override @SuppressWarnings("unchecked") public Mono<FluentT> createResourceAsync() { this.webAppMsiHandler.processCreatedExternalIdentities(); this.webAppMsiHandler.handleExternalIdentities(); return submitSite(innerModel()) .map( siteInner -> { setInner(siteInner); return (FluentT) WebAppBaseImpl.this; }); } @Override @SuppressWarnings("unchecked") public Mono<FluentT> updateResourceAsync() { SiteInner siteInner = this.innerModel(); SitePatchResourceInner siteUpdate = new SitePatchResourceInner(); siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates()); siteUpdate.withKind(siteInner.kind()); siteUpdate.withEnabled(siteInner.enabled()); siteUpdate.withServerFarmId(siteInner.serverFarmId()); siteUpdate.withReserved(siteInner.reserved()); siteUpdate.withIsXenon(siteInner.isXenon()); siteUpdate.withHyperV(siteInner.hyperV()); siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped()); siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile()); siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled()); siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled()); siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths()); siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled()); siteUpdate.withContainerSize(siteInner.containerSize()); siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota()); siteUpdate.withCloningInfo(siteInner.cloningInfo()); siteUpdate.withHttpsOnly(siteInner.httpsOnly()); siteUpdate.withRedundancyMode(siteInner.redundancyMode()); this.webAppMsiHandler.handleExternalIdentities(siteUpdate); return submitSite(siteUpdate) .map( siteInner1 -> { setInner(siteInner1); webAppMsiHandler.clear(); return (FluentT) WebAppBaseImpl.this; }); } @Override public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) { if (!isGroupFaulted) { isInCreateMode = false; initializeKuduClient(); } return Mono .fromCallable( () -> { normalizeProperties(); return null; }); } Mono<SiteInner> submitSite(final SiteInner site) { site.withSiteConfig(new SiteConfigInner()); return submitSiteWithoutSiteConfig(site); } Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) { return createOrUpdateInner(site) .map( siteInner -> { site.withSiteConfig(null); return siteInner; }); } Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) { return updateInner(siteUpdate) .map( siteInner -> { siteInner.withSiteConfig(null); return siteInner; }); } @SuppressWarnings("unchecked") Mono<FluentT> submitHostNameBindings() { final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>(); for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) { bindingObservables.add(binding.createAsync()); } for (String binding : hostNameBindingsToDelete) { bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty())); } if (bindingObservables.isEmpty()) { return Mono.just((FluentT) this); } else { return Flux .zip(bindingObservables, ignored -> WebAppBaseImpl.this) .last() .onErrorResume( throwable -> { if (throwable instanceof HttpResponseException && ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) { return submitSite(innerModel()) .flatMap( ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last()); } else { return Mono.error(throwable); } }) .flatMap(WebAppBaseImpl::refreshAsync); } } Mono<Indexable> submitSslBindings(final SiteInner site) { List<Mono<AppServiceCertificate>> certs = new ArrayList<>(); for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) { certs.add(binding.newCertificate()); hostNameSslStateMap.put(binding.innerModel().name(), binding.innerModel().withToUpdate(true)); } if (certs.isEmpty()) { return Mono.just((Indexable) this); } else { site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values())); return Flux .zip(certs, ignored -> site) .last() .flatMap(this::createOrUpdateInner) .map( siteInner -> { setInner(siteInner); return WebAppBaseImpl.this; }); } } Mono<Indexable> submitAppSettings() { Mono<Indexable> observable = Mono.just((Indexable) this); if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) { observable = listAppSettings() .switchIfEmpty(Mono.just(new StringDictionaryInner())) .flatMap( stringDictionaryInner -> { if (stringDictionaryInner.properties() == null) { stringDictionaryInner.withProperties(new HashMap<String, String>()); } for (String appSettingKey : appSettingsToRemove) { stringDictionaryInner.properties().remove(appSettingKey); } stringDictionaryInner.properties().putAll(appSettingsToAdd); return updateAppSettings(stringDictionaryInner); }) .map(ignored -> WebAppBaseImpl.this); } return observable; } Mono<Indexable> submitMetadata() { return Mono.just((Indexable) this); } Mono<Indexable> submitConnectionStrings() { Mono<Indexable> observable = Mono.just((Indexable) this); if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) { observable = listConnectionStrings() .switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner())) .flatMap( dictionaryInner -> { if (dictionaryInner.properties() == null) { dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>()); } for (String connectionString : connectionStringsToRemove) { dictionaryInner.properties().remove(connectionString); } dictionaryInner.properties().putAll(connectionStringsToAdd); return updateConnectionStrings(dictionaryInner); }) .map(ignored -> WebAppBaseImpl.this); } return observable; } Mono<Indexable> submitStickiness() { Mono<Indexable> observable = Mono.just((Indexable) this); if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) { observable = listSlotConfigurations() .switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner())) .flatMap( slotConfigNamesResourceInner -> { if (slotConfigNamesResourceInner.appSettingNames() == null) { slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>()); } if (slotConfigNamesResourceInner.connectionStringNames() == null) { slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>()); } Set<String> stickyAppSettingKeys = new HashSet<>(slotConfigNamesResourceInner.appSettingNames()); Set<String> stickyConnectionStringNames = new HashSet<>(slotConfigNamesResourceInner.connectionStringNames()); for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) { if (stickiness.getValue()) { stickyAppSettingKeys.add(stickiness.getKey()); } else { stickyAppSettingKeys.remove(stickiness.getKey()); } } for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) { if (stickiness.getValue()) { stickyConnectionStringNames.add(stickiness.getKey()); } else { stickyConnectionStringNames.remove(stickiness.getKey()); } } slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys)); slotConfigNamesResourceInner .withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames)); return updateSlotConfigurations(slotConfigNamesResourceInner); }) .map(ignored -> WebAppBaseImpl.this); } return observable; } Mono<Indexable> submitSourceControlToCreate() { if (sourceControl == null || sourceControlToDelete) { return Mono.just((Indexable) this); } return sourceControl .registerGithubAccessToken() .then(createOrUpdateSourceControl(sourceControl.innerModel())) .delayElement(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(30))) .map(ignored -> WebAppBaseImpl.this); } Mono<Indexable> submitSourceControlToDelete() { if (!sourceControlToDelete) { return Mono.just((Indexable) this); } return deleteSourceControl().map(ignored -> WebAppBaseImpl.this); } Mono<Indexable> submitAuthentication() { if (!authenticationToUpdate) { return Mono.just((Indexable) this); } return updateAuthentication(authentication.innerModel()) .map( siteAuthSettingsInner -> { WebAppBaseImpl.this.authentication = new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this); return WebAppBaseImpl.this; }); } Mono<Indexable> submitLogConfiguration() { if (!diagnosticLogsToUpdate) { return Mono.just((Indexable) this); } return updateDiagnosticLogsConfig(diagnosticLogs.innerModel()) .map( siteLogsConfigInner -> { WebAppBaseImpl.this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this); return WebAppBaseImpl.this; }); } @Override public WebDeploymentImpl<FluentT, FluentImplT> deploy() { return new WebDeploymentImpl<>(this); } WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding( final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) { sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding); return this; } @SuppressWarnings("unchecked") public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) { for (String hostname : hostnames) { if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) { defineHostnameBinding() .withAzureManagedDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.A) .attach(); } else { defineHostnameBinding() .withAzureManagedDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) .attach(); } } return (FluentImplT) this; } @SuppressWarnings("unchecked") public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() { HostnameBindingInner inner = new HostnameBindingInner(); inner.withSiteName(name()); inner.withAzureResourceType(AzureResourceType.WEBSITE); inner.withAzureResourceName(name()); inner.withHostnameType(HostnameType.VERIFIED); return new HostnameBindingImpl<>(inner, (FluentImplT) this); } @SuppressWarnings("unchecked") public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) { for (String hostname : hostnames) { defineHostnameBinding() .withThirdPartyDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) .attach(); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutHostnameBinding(String hostname) { hostNameBindingsToDelete.add(hostname); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutSslBinding(String hostname) { if (hostNameSslStateMap.containsKey(hostname)) { hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true); } return (FluentImplT) this; } @SuppressWarnings("unchecked") FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) { this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppDisabledOnCreation() { innerModel().withEnabled(false); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) { innerModel().withScmSiteAlsoStopped(scmSiteAlsoStopped); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withClientAffinityEnabled(boolean enabled) { innerModel().withClientAffinityEnabled(enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withClientCertEnabled(boolean enabled) { innerModel().withClientCertEnabled(enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() { return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this); } @SuppressWarnings("unchecked") public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withNetFrameworkVersion(version.toString()); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withPhpVersion(PhpVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withPhpVersion(version.toString()); return (FluentImplT) this; } public FluentImplT withoutPhp() { return withPhpVersion(PhpVersion.fromString("")); } @SuppressWarnings("unchecked") public FluentImplT withJavaVersion(JavaVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withJavaVersion(version.toString()); return (FluentImplT) this; } public FluentImplT withoutJava() { return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString("")); } @SuppressWarnings("unchecked") public FluentImplT withWebContainer(WebContainer webContainer) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (webContainer == null) { siteConfig.withJavaContainer(null); siteConfig.withJavaContainerVersion(null); } else if (webContainer.toString().isEmpty()) { siteConfig.withJavaContainer(""); siteConfig.withJavaContainerVersion(""); } else { String[] containerInfo = webContainer.toString().split(" "); siteConfig.withJavaContainer(containerInfo[0]); siteConfig.withJavaContainerVersion(containerInfo[1]); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withPythonVersion(PythonVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withPythonVersion(version.toString()); return (FluentImplT) this; } public FluentImplT withoutPython() { return withPythonVersion(PythonVersion.fromString("")); } @SuppressWarnings("unchecked") public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86)); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withWebSocketsEnabled(boolean enabled) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withWebSocketsEnabled(enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withAlwaysOn(alwaysOn); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withManagedPipelineMode(managedPipelineMode); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAutoSwapSlotName(String slotName) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withAutoSwapSlotName(slotName); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withRemoteDebuggingEnabled(true); siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString()); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withRemoteDebuggingDisabled() { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withRemoteDebuggingEnabled(false); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withDefaultDocument(String document) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (siteConfig.defaultDocuments() == null) { siteConfig.withDefaultDocuments(new ArrayList<String>()); } siteConfig.defaultDocuments().add(document); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withDefaultDocuments(List<String> documents) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (siteConfig.defaultDocuments() == null) { siteConfig.withDefaultDocuments(new ArrayList<>()); } siteConfig.defaultDocuments().addAll(documents); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutDefaultDocument(String document) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (siteConfig.defaultDocuments() != null) { siteConfig.defaultDocuments().remove(document); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withHttpsOnly(boolean httpsOnly) { innerModel().withHttpsOnly(httpsOnly); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withHttp20Enabled(boolean http20Enabled) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withHttp20Enabled(http20Enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withFtpsState(FtpsState ftpsState) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withFtpsState(ftpsState); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withVirtualApplications(virtualApplications); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withMinTlsVersion(minTlsVersion); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppSetting(String key, String value) { appSettingsToAdd.put(key, value); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppSettings(Map<String, String> settings) { appSettingsToAdd.putAll(settings); return (FluentImplT) this; } public FluentImplT withStickyAppSetting(String key, String value) { withAppSetting(key, value); return withAppSettingStickiness(key, true); } @SuppressWarnings("unchecked") public FluentImplT withStickyAppSettings(Map<String, String> settings) { withAppSettings(settings); for (String key : settings.keySet()) { appSettingStickiness.put(key, true); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutAppSetting(String key) { appSettingsToRemove.add(key); appSettingStickiness.remove(key); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppSettingStickiness(String key, boolean sticky) { appSettingStickiness.put(key, sticky); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) { connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type)); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) { connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type)); connectionStringStickiness.put(name, true); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutConnectionString(String name) { connectionStringsToRemove.add(name); connectionStringStickiness.remove(name); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) { connectionStringStickiness.put(name, stickiness); return (FluentImplT) this; } @SuppressWarnings("unchecked") void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) { this.sourceControl = sourceControl; } public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() { SiteSourceControlInner sourceControlInner = new SiteSourceControlInner(); return new WebAppSourceControlImpl<>(sourceControlInner, this); } @SuppressWarnings("unchecked") public FluentImplT withLocalGitSourceControl() { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withScmType(ScmType.LOCAL_GIT); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutSourceControl() { sourceControlToDelete = true; return (FluentImplT) this; } @SuppressWarnings("unchecked") void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) { this.authentication = authentication; authenticationToUpdate = true; } void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) { this.diagnosticLogs = diagnosticLogs; diagnosticLogsToUpdate = true; } @Override @SuppressWarnings("unchecked") public Mono<FluentT> refreshAsync() { return super .refreshAsync() .flatMap( fluentT -> getConfigInner() .map( returnedSiteConfig -> { siteConfig = returnedSiteConfig; return fluentT; })); } @Override protected Mono<SiteInner> getInnerAsync() { return getInner(); } @Override public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() { return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this); } @Override @SuppressWarnings("unchecked") public FluentImplT withoutAuthentication() { this.authentication.innerModel().withEnabled(false); authenticationToUpdate = true; return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) { return updateDiagnosticLogsConfiguration() .withWebServerLogging() .withWebServerLogsStoredOnFileSystem() .withWebServerFileSystemQuotaInMB(quotaInMB) .withLogRetentionDays(retentionDays) .attach(); } @Override public FluentImplT withContainerLoggingEnabled() { return withContainerLoggingEnabled(35, 0); } @Override @SuppressWarnings("unchecked") public FluentImplT withContainerLoggingDisabled() { return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach(); } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedManagedServiceIdentity() { this.webAppMsiHandler.withLocalManagedServiceIdentity(); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withoutSystemAssignedManagedServiceIdentity() { this.webAppMsiHandler.withoutLocalManagedServiceIdentity(); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withUserAssignedManagedServiceIdentity() { return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) { this.webAppMsiHandler.withAccessTo(resourceId, role); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) { this.webAppMsiHandler.withAccessToCurrentResourceGroup(role); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) { this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) { this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) { this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) { this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) { this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId); return (FluentImplT) this; } @Override public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() { if (diagnosticLogs == null) { return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this); } else { return diagnosticLogs; } } @Override public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() { return defineDiagnosticLogsConfiguration(); } @Override public ManagedServiceIdentity identity() { return webSiteBase.identity(); } @Override public boolean hyperV() { return webSiteBase.hyperV(); } @Override public HostingEnvironmentProfile hostingEnvironmentProfile() { return webSiteBase.hostingEnvironmentProfile(); } @Override public Set<String> clientCertExclusionPaths() { return webSiteBase.clientCertExclusionPaths(); } @Override public Set<String> possibleOutboundIpAddresses() { return webSiteBase.possibleOutboundIpAddresses(); } @Override public int dailyMemoryTimeQuota() { return webSiteBase.dailyMemoryTimeQuota(); } @Override public OffsetDateTime suspendedTill() { return webSiteBase.suspendedTill(); } @Override public int maxNumberOfWorkers() { return webSiteBase.maxNumberOfWorkers(); } @Override public SlotSwapStatus slotSwapStatus() { return webSiteBase.slotSwapStatus(); } @Override public RedundancyMode redundancyMode() { return webSiteBase.redundancyMode(); } private static class PipedInputStreamWithCallback extends PipedInputStream { private Runnable callback; private void addCallback(Runnable action) { this.callback = action; } @Override public void close() throws IOException { callback.run(); super.close(); } } protected void setAppFrameworkVersion(String fxVersion) { if (operatingSystem() == OperatingSystem.LINUX) { siteConfig.withLinuxFxVersion(fxVersion); } else { siteConfig.withWindowsFxVersion(fxVersion); } } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessFromAllNetworks() { this.ensureIpSecurityRestrictions(); this.siteConfig.withIpSecurityRestrictions(new ArrayList<>()); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessFromNetworkSubnet(String subnetId, int priority) { this.ensureIpSecurityRestrictions(); this.siteConfig.ipSecurityRestrictions().add(new IpSecurityRestriction() .withAction(IP_RESTRICTION_ACTION_ALLOW) .withPriority(priority) .withTag(IpFilterTag.DEFAULT) .withVnetSubnetResourceId(subnetId)); return (FluentImplT) this; } @Override public FluentImplT withAccessFromIpAddress(String ipAddress, int priority) { String ipAddressCidr = ipAddress.contains("/") ? ipAddress : ipAddress + "/32"; return withAccessFromIpAddressRange(ipAddressCidr, priority); } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessFromIpAddressRange(String ipAddressCidr, int priority) { this.ensureIpSecurityRestrictions(); this.siteConfig.ipSecurityRestrictions().add(new IpSecurityRestriction() .withAction(IP_RESTRICTION_ACTION_ALLOW) .withPriority(priority) .withTag(IpFilterTag.DEFAULT) .withIpAddress(ipAddressCidr)); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessRule(IpSecurityRestriction ipSecurityRule) { this.ensureIpSecurityRestrictions(); this.siteConfig.ipSecurityRestrictions().add(ipSecurityRule); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withoutNetworkSubnetAccess(String subnetId) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() .filter(r -> !(IP_RESTRICTION_ACTION_ALLOW.equalsIgnoreCase(r.action()) && IpFilterTag.DEFAULT == r.tag() && subnetId.equalsIgnoreCase(r.vnetSubnetResourceId()))) .collect(Collectors.toList()) ); } return (FluentImplT) this; } @Override public FluentImplT withoutIpAddressAccess(String ipAddress) { String ipAddressCidr = ipAddress.contains("/") ? ipAddress : ipAddress + "/32"; return withoutIpAddressRangeAccess(ipAddressCidr); } @Override @SuppressWarnings("unchecked") public FluentImplT withoutIpAddressRangeAccess(String ipAddressCidr) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() .filter(r -> !(IP_RESTRICTION_ACTION_ALLOW.equalsIgnoreCase(r.action()) && IpFilterTag.DEFAULT == r.tag() && Objects.equals(ipAddressCidr, r.ipAddress()))) .collect(Collectors.toList()) ); } return (FluentImplT) this; } @Override public Map<String, String> getSiteAppSettings() { return getSiteAppSettingsAsync().block(); } @Override public Mono<Map<String, String>> getSiteAppSettingsAsync() { return kuduClient.settings(); } @Override @SuppressWarnings("unchecked") public FluentImplT withoutAccessRule(IpSecurityRestriction ipSecurityRule) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() .filter(r -> !(Objects.equals(r.action(), ipSecurityRule.action()) && Objects.equals(r.tag(), ipSecurityRule.tag()) && (Objects.equals(r.ipAddress(), ipSecurityRule.ipAddress()) || Objects.equals(r.vnetSubnetResourceId(), ipSecurityRule.vnetSubnetResourceId())))) .collect(Collectors.toList()) ); } return (FluentImplT) this; } private void ensureIpSecurityRestrictions() { if (this.siteConfig == null) { this.siteConfig = new SiteConfigResourceInner(); } if (this.siteConfig.ipSecurityRestrictions() == null) { this.siteConfig.withIpSecurityRestrictions(new ArrayList<>()); } } protected static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.appservice.models.PrivateLinkResource innerModel; protected PrivateLinkResourceImpl(com.azure.resourcemanager.appservice.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.properties().groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.properties().requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.properties().requiredZoneNames()); } } protected static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final RemotePrivateEndpointConnectionArmResourceInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; protected PrivateEndpointConnectionImpl(RemotePrivateEndpointConnectionArmResourceInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionsRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>> extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager> implements WebAppBase, WebAppBase.Definition<FluentT>, WebAppBase.Update<FluentT>, WebAppBase.UpdateStages.WithWebContainer<FluentT> { private final ClientLogger logger = new ClientLogger(getClass()); protected static final String SETTING_DOCKER_IMAGE = "DOCKER_CUSTOM_IMAGE_NAME"; protected static final String SETTING_REGISTRY_SERVER = "DOCKER_REGISTRY_SERVER_URL"; protected static final String SETTING_REGISTRY_USERNAME = "DOCKER_REGISTRY_SERVER_USERNAME"; protected static final String SETTING_REGISTRY_PASSWORD = "DOCKER_REGISTRY_SERVER_PASSWORD"; protected static final String SETTING_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; protected static final String SETTING_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; protected static final String IP_RESTRICTION_ACTION_ALLOW = "Allow"; protected static final String IP_RESTRICTION_ACTION_DENY = "Deny"; private static final Map<AzureEnvironment, String> DNS_MAP = new HashMap<AzureEnvironment, String>() { { put(AzureEnvironment.AZURE, "azurewebsites.net"); put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn"); put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de"); put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us"); } }; SiteConfigResourceInner siteConfig; KuduClient kuduClient; WebSiteBase webSiteBase; private Map<String, HostnameSslState> hostNameSslStateMap; private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate; private List<String> hostNameBindingsToDelete; private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate; protected Map<String, String> appSettingsToAdd; protected List<String> appSettingsToRemove; private Map<String, Boolean> appSettingStickiness; private Map<String, ConnStringValueTypePair> connectionStringsToAdd; private List<String> connectionStringsToRemove; private Map<String, Boolean> connectionStringStickiness; private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl; private boolean sourceControlToDelete; private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication; private boolean authenticationToUpdate; private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs; private boolean diagnosticLogsToUpdate; private FunctionalTaskItem msiHandler; private boolean isInCreateMode; private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler; WebAppBaseImpl( String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, manager); if (innerObject != null && innerObject.kind() != null) { innerObject.withKind(innerObject.kind().replace(";", ",")); } this.siteConfig = siteConfig; if (logConfig != null) { this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this); } webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this); normalizeProperties(); isInCreateMode = innerModel() == null || innerModel().id() == null; if (!isInCreateMode) { initializeKuduClient(); } } public boolean isInCreateMode() { return isInCreateMode; } private void initializeKuduClient() { if (kuduClient == null) { kuduClient = new KuduClient(this); } } @Override public void setInner(SiteInner innerObject) { if (innerObject.kind() != null) { innerObject.withKind(innerObject.kind().replace(";", ",")); } super.setInner(innerObject); } RoleAssignmentHelper.IdProvider idProvider() { return new RoleAssignmentHelper.IdProvider() { @Override public String principalId() { if (innerModel() != null && innerModel().identity() != null) { return innerModel().identity().principalId(); } else { return null; } } @Override public String resourceId() { if (innerModel() != null) { return innerModel().id(); } else { return null; } } }; } private void normalizeProperties() { this.hostNameBindingsToCreate = new TreeMap<>(); this.hostNameBindingsToDelete = new ArrayList<>(); this.appSettingsToAdd = new HashMap<>(); this.appSettingsToRemove = new ArrayList<>(); this.appSettingStickiness = new HashMap<>(); this.connectionStringsToAdd = new HashMap<>(); this.connectionStringsToRemove = new ArrayList<>(); this.connectionStringStickiness = new HashMap<>(); this.sourceControl = null; this.sourceControlToDelete = false; this.authenticationToUpdate = false; this.diagnosticLogsToUpdate = false; this.sslBindingsToCreate = new TreeMap<>(); this.msiHandler = null; this.webSiteBase = new WebSiteBaseImpl(innerModel()); this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates()); this.webAppMsiHandler.clear(); } @Override public String state() { return webSiteBase.state(); } @Override public Set<String> hostnames() { return webSiteBase.hostnames(); } @Override public String repositorySiteName() { return webSiteBase.repositorySiteName(); } @Override public UsageState usageState() { return webSiteBase.usageState(); } @Override public boolean enabled() { return webSiteBase.enabled(); } @Override public Set<String> enabledHostNames() { return webSiteBase.enabledHostNames(); } @Override public SiteAvailabilityState availabilityState() { return webSiteBase.availabilityState(); } @Override public Map<String, HostnameSslState> hostnameSslStates() { return Collections.unmodifiableMap(hostNameSslStateMap); } @Override public String appServicePlanId() { return webSiteBase.appServicePlanId(); } @Override public OffsetDateTime lastModifiedTime() { return webSiteBase.lastModifiedTime(); } @Override public Set<String> trafficManagerHostNames() { return webSiteBase.trafficManagerHostNames(); } @Override public boolean scmSiteAlsoStopped() { return webSiteBase.scmSiteAlsoStopped(); } @Override public String targetSwapSlot() { return webSiteBase.targetSwapSlot(); } @Override public boolean clientAffinityEnabled() { return webSiteBase.clientAffinityEnabled(); } @Override public boolean clientCertEnabled() { return webSiteBase.clientCertEnabled(); } @Override public boolean hostnamesDisabled() { return webSiteBase.hostnamesDisabled(); } @Override public Set<String> outboundIPAddresses() { return webSiteBase.outboundIPAddresses(); } @Override public int containerSize() { return webSiteBase.containerSize(); } @Override public CloningInfo cloningInfo() { return webSiteBase.cloningInfo(); } @Override public boolean isDefaultContainer() { return webSiteBase.isDefaultContainer(); } @Override public String defaultHostname() { if (innerModel().defaultHostname() != null) { return innerModel().defaultHostname(); } else { AzureEnvironment environment = manager().environment(); String dns = DNS_MAP.get(environment); String leaf = name(); if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) { leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf; } return leaf + "." + dns; } } @Override public List<String> defaultDocuments() { if (siteConfig == null) { return null; } return Collections.unmodifiableList(siteConfig.defaultDocuments()); } @Override public NetFrameworkVersion netFrameworkVersion() { if (siteConfig == null) { return null; } return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion()); } @Override public PhpVersion phpVersion() { if (siteConfig == null || siteConfig.phpVersion() == null) { return PhpVersion.OFF; } return PhpVersion.fromString(siteConfig.phpVersion()); } @Override public PythonVersion pythonVersion() { if (siteConfig == null || siteConfig.pythonVersion() == null) { return PythonVersion.OFF; } return PythonVersion.fromString(siteConfig.pythonVersion()); } @Override public String nodeVersion() { if (siteConfig == null) { return null; } return siteConfig.nodeVersion(); } @Override public boolean remoteDebuggingEnabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled()); } @Override public RemoteVisualStudioVersion remoteDebuggingVersion() { if (siteConfig == null) { return null; } return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion()); } @Override public boolean webSocketsEnabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.webSocketsEnabled()); } @Override public boolean alwaysOn() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.alwaysOn()); } @Override public JavaVersion javaVersion() { if (siteConfig == null || siteConfig.javaVersion() == null) { return JavaVersion.OFF; } return JavaVersion.fromString(siteConfig.javaVersion()); } @Override public String javaContainer() { if (siteConfig == null) { return null; } return siteConfig.javaContainer(); } @Override public String javaContainerVersion() { if (siteConfig == null) { return null; } return siteConfig.javaContainerVersion(); } @Override public ManagedPipelineMode managedPipelineMode() { if (siteConfig == null) { return null; } return siteConfig.managedPipelineMode(); } @Override public PlatformArchitecture platformArchitecture() { if (siteConfig.use32BitWorkerProcess()) { return PlatformArchitecture.X86; } else { return PlatformArchitecture.X64; } } @Override public String linuxFxVersion() { if (siteConfig == null) { return null; } return siteConfig.linuxFxVersion(); } @Override public String windowsFxVersion() { if (siteConfig == null) { return null; } return siteConfig.windowsFxVersion(); } @Override public String autoSwapSlotName() { if (siteConfig == null) { return null; } return siteConfig.autoSwapSlotName(); } @Override public boolean httpsOnly() { return webSiteBase.httpsOnly(); } @Override public FtpsState ftpsState() { if (siteConfig == null) { return null; } return siteConfig.ftpsState(); } @Override public List<VirtualApplication> virtualApplications() { if (siteConfig == null) { return null; } return siteConfig.virtualApplications(); } @Override public boolean http20Enabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.http20Enabled()); } @Override public boolean localMySqlEnabled() { if (siteConfig == null) { return false; } return ResourceManagerUtils.toPrimitiveBoolean(siteConfig.localMySqlEnabled()); } @Override public ScmType scmType() { if (siteConfig == null) { return null; } return siteConfig.scmType(); } @Override public String documentRoot() { if (siteConfig == null) { return null; } return siteConfig.documentRoot(); } @Override public SupportedTlsVersions minTlsVersion() { if (siteConfig == null) { return null; } return siteConfig.minTlsVersion(); } @Override public List<IpSecurityRestriction> ipSecurityRules() { if (this.siteConfig == null || this.siteConfig.ipSecurityRestrictions() == null) { return Collections.emptyList(); } return Collections.unmodifiableList(siteConfig.ipSecurityRestrictions()); } @Override public OperatingSystem operatingSystem() { if (innerModel().kind() != null && innerModel().kind().toLowerCase(Locale.ROOT).contains("linux")) { return OperatingSystem.LINUX; } else { return OperatingSystem.WINDOWS; } } @Override public String systemAssignedManagedServiceIdentityTenantId() { if (innerModel().identity() == null) { return null; } return innerModel().identity().tenantId(); } @Override public String systemAssignedManagedServiceIdentityPrincipalId() { if (innerModel().identity() == null) { return null; } return innerModel().identity().principalId(); } @Override public Set<String> userAssignedManagedServiceIdentityIds() { if (innerModel().identity() == null) { return null; } return innerModel().identity().userAssignedIdentities().keySet(); } @Override public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() { return diagnosticLogs; } @Override public InputStream streamApplicationLogs() { return pipeObservableToInputStream(streamApplicationLogsAsync()); } @Override public Flux<String> streamApplicationLogsAsync() { return kuduClient.streamApplicationLogsAsync(); } @Override public InputStream streamHttpLogs() { return pipeObservableToInputStream(streamHttpLogsAsync()); } @Override public Flux<String> streamHttpLogsAsync() { return kuduClient.streamHttpLogsAsync(); } @Override public InputStream streamTraceLogs() { return pipeObservableToInputStream(streamTraceLogsAsync()); } @Override public Flux<String> streamTraceLogsAsync() { return kuduClient.streamTraceLogsAsync(); } @Override public InputStream streamDeploymentLogs() { return pipeObservableToInputStream(streamDeploymentLogsAsync()); } @Override public Flux<String> streamDeploymentLogsAsync() { return kuduClient.streamDeploymentLogsAsync(); } @Override public InputStream streamAllLogs() { return pipeObservableToInputStream(streamAllLogsAsync()); } @Override public Flux<String> streamAllLogsAsync() { return kuduClient.streamAllLogsAsync(); } private InputStream pipeObservableToInputStream(Flux<String> observable) { PipedInputStreamWithCallback in = new PipedInputStreamWithCallback(); final PipedOutputStream out = new PipedOutputStream(); try { in.connect(out); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } final Disposable subscription = observable .subscribeOn(Schedulers.boundedElastic()) .subscribe( s -> { try { out.write(s.getBytes(StandardCharsets.UTF_8)); out.write('\n'); out.flush(); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } }); in .addCallback( () -> { subscription.dispose(); try { out.close(); } catch (IOException e) { e.printStackTrace(); } }); return in; } @Override public Map<String, AppSetting> getAppSettings() { return getAppSettingsAsync().block(); } @Override public Mono<Map<String, AppSetting>> getAppSettingsAsync() { return Mono .zip( listAppSettings(), listSlotConfigurations(), (appSettingsInner, slotConfigs) -> appSettingsInner .properties() .entrySet() .stream() .collect( Collectors .toMap( Map.Entry::getKey, entry -> new AppSettingImpl( entry.getKey(), entry.getValue(), slotConfigs.appSettingNames() != null && slotConfigs.appSettingNames().contains(entry.getKey()))))); } @Override public Map<String, ConnectionString> getConnectionStrings() { return getConnectionStringsAsync().block(); } @Override public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() { return Mono .zip( listConnectionStrings(), listSlotConfigurations(), (connectionStringsInner, slotConfigs) -> connectionStringsInner .properties() .entrySet() .stream() .collect( Collectors .toMap( Map.Entry::getKey, entry -> new ConnectionStringImpl( entry.getKey(), entry.getValue(), slotConfigs.connectionStringNames() != null && slotConfigs.connectionStringNames().contains(entry.getKey()))))); } @Override public WebAppAuthentication getAuthenticationConfig() { return getAuthenticationConfigAsync().block(); } @Override public Mono<WebAppAuthentication> getAuthenticationConfigAsync() { return getAuthentication() .map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this)); } abstract Mono<SiteInner> createOrUpdateInner(SiteInner site); abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate); abstract Mono<SiteInner> getInner(); abstract Mono<SiteConfigResourceInner> getConfigInner(); abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig); abstract Mono<Void> deleteHostnameBinding(String hostname); abstract Mono<StringDictionaryInner> listAppSettings(); abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner); abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings(); abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner); abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations(); abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner); abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner); abstract Mono<Void> deleteSourceControl(); abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner); abstract Mono<SiteAuthSettingsInner> getAuthentication(); abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner); abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner); @Override public void beforeGroupCreateOrUpdate() { if (hostNameSslStateMap.size() > 0) { innerModel().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values())); } IndexableTaskItem rootTaskItem = wrapTask( context -> { return submitHostNameBindings() .flatMap(fluentT -> submitSslBindings(fluentT.innerModel())); }); IndexableTaskItem lastTaskItem = rootTaskItem; lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig()); lastTaskItem = sequentialTask( lastTaskItem, context -> submitMetadata() .flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last()) .flatMap(ignored -> submitStickiness())); lastTaskItem = sequentialTask( lastTaskItem, context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate())); lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication()); lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration()); if (msiHandler != null) { sequentialTask(lastTaskItem, msiHandler); } addPostRunDependent(rootTaskItem); } private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) { return IndexableTaskItem.create(taskItem); } private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) { IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2); taskItem1.addPostRunDependent(taskItem); return taskItem; } @Override @SuppressWarnings("unchecked") public Mono<FluentT> createResourceAsync() { this.webAppMsiHandler.processCreatedExternalIdentities(); this.webAppMsiHandler.handleExternalIdentities(); return submitSite(innerModel()) .map( siteInner -> { setInner(siteInner); return (FluentT) WebAppBaseImpl.this; }); } @Override @SuppressWarnings("unchecked") public Mono<FluentT> updateResourceAsync() { SiteInner siteInner = this.innerModel(); SitePatchResourceInner siteUpdate = new SitePatchResourceInner(); siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates()); siteUpdate.withKind(siteInner.kind()); siteUpdate.withEnabled(siteInner.enabled()); siteUpdate.withServerFarmId(siteInner.serverFarmId()); siteUpdate.withReserved(siteInner.reserved()); siteUpdate.withIsXenon(siteInner.isXenon()); siteUpdate.withHyperV(siteInner.hyperV()); siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped()); siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile()); siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled()); siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled()); siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths()); siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled()); siteUpdate.withContainerSize(siteInner.containerSize()); siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota()); siteUpdate.withCloningInfo(siteInner.cloningInfo()); siteUpdate.withHttpsOnly(siteInner.httpsOnly()); siteUpdate.withRedundancyMode(siteInner.redundancyMode()); this.webAppMsiHandler.handleExternalIdentities(siteUpdate); return submitSite(siteUpdate) .map( siteInner1 -> { setInner(siteInner1); webAppMsiHandler.clear(); return (FluentT) WebAppBaseImpl.this; }); } @Override public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) { if (!isGroupFaulted) { isInCreateMode = false; initializeKuduClient(); } return Mono .fromCallable( () -> { normalizeProperties(); return null; }); } Mono<SiteInner> submitSite(final SiteInner site) { site.withSiteConfig(new SiteConfigInner()); return submitSiteWithoutSiteConfig(site); } Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) { return createOrUpdateInner(site) .map( siteInner -> { site.withSiteConfig(null); return siteInner; }); } Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) { return updateInner(siteUpdate) .map( siteInner -> { siteInner.withSiteConfig(null); return siteInner; }); } @SuppressWarnings("unchecked") Mono<FluentT> submitHostNameBindings() { final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>(); for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) { bindingObservables.add(binding.createAsync()); } for (String binding : hostNameBindingsToDelete) { bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty())); } if (bindingObservables.isEmpty()) { return Mono.just((FluentT) this); } else { return Flux .zip(bindingObservables, ignored -> WebAppBaseImpl.this) .last() .onErrorResume( throwable -> { if (throwable instanceof HttpResponseException && ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) { return submitSite(innerModel()) .flatMap( ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last()); } else { return Mono.error(throwable); } }) .flatMap(WebAppBaseImpl::refreshAsync); } } Mono<Indexable> submitSslBindings(final SiteInner site) { List<Mono<AppServiceCertificate>> certs = new ArrayList<>(); for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) { certs.add(binding.newCertificate()); hostNameSslStateMap.put(binding.innerModel().name(), binding.innerModel().withToUpdate(true)); } if (certs.isEmpty()) { return Mono.just((Indexable) this); } else { site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values())); return Flux .zip(certs, ignored -> site) .last() .flatMap(this::createOrUpdateInner) .map( siteInner -> { setInner(siteInner); return WebAppBaseImpl.this; }); } } Mono<Indexable> submitAppSettings() { Mono<Indexable> observable = Mono.just((Indexable) this); if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) { observable = listAppSettings() .switchIfEmpty(Mono.just(new StringDictionaryInner())) .flatMap( stringDictionaryInner -> { if (stringDictionaryInner.properties() == null) { stringDictionaryInner.withProperties(new HashMap<String, String>()); } for (String appSettingKey : appSettingsToRemove) { stringDictionaryInner.properties().remove(appSettingKey); } stringDictionaryInner.properties().putAll(appSettingsToAdd); return updateAppSettings(stringDictionaryInner); }) .map(ignored -> WebAppBaseImpl.this); } return observable; } Mono<Indexable> submitMetadata() { return Mono.just((Indexable) this); } Mono<Indexable> submitConnectionStrings() { Mono<Indexable> observable = Mono.just((Indexable) this); if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) { observable = listConnectionStrings() .switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner())) .flatMap( dictionaryInner -> { if (dictionaryInner.properties() == null) { dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>()); } for (String connectionString : connectionStringsToRemove) { dictionaryInner.properties().remove(connectionString); } dictionaryInner.properties().putAll(connectionStringsToAdd); return updateConnectionStrings(dictionaryInner); }) .map(ignored -> WebAppBaseImpl.this); } return observable; } Mono<Indexable> submitStickiness() { Mono<Indexable> observable = Mono.just((Indexable) this); if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) { observable = listSlotConfigurations() .switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner())) .flatMap( slotConfigNamesResourceInner -> { if (slotConfigNamesResourceInner.appSettingNames() == null) { slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>()); } if (slotConfigNamesResourceInner.connectionStringNames() == null) { slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>()); } Set<String> stickyAppSettingKeys = new HashSet<>(slotConfigNamesResourceInner.appSettingNames()); Set<String> stickyConnectionStringNames = new HashSet<>(slotConfigNamesResourceInner.connectionStringNames()); for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) { if (stickiness.getValue()) { stickyAppSettingKeys.add(stickiness.getKey()); } else { stickyAppSettingKeys.remove(stickiness.getKey()); } } for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) { if (stickiness.getValue()) { stickyConnectionStringNames.add(stickiness.getKey()); } else { stickyConnectionStringNames.remove(stickiness.getKey()); } } slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys)); slotConfigNamesResourceInner .withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames)); return updateSlotConfigurations(slotConfigNamesResourceInner); }) .map(ignored -> WebAppBaseImpl.this); } return observable; } Mono<Indexable> submitSourceControlToCreate() { if (sourceControl == null || sourceControlToDelete) { return Mono.just((Indexable) this); } return sourceControl .registerGithubAccessToken() .then(createOrUpdateSourceControl(sourceControl.innerModel())) .delayElement(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(30))) .map(ignored -> WebAppBaseImpl.this); } Mono<Indexable> submitSourceControlToDelete() { if (!sourceControlToDelete) { return Mono.just((Indexable) this); } return deleteSourceControl().map(ignored -> WebAppBaseImpl.this); } Mono<Indexable> submitAuthentication() { if (!authenticationToUpdate) { return Mono.just((Indexable) this); } return updateAuthentication(authentication.innerModel()) .map( siteAuthSettingsInner -> { WebAppBaseImpl.this.authentication = new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this); return WebAppBaseImpl.this; }); } Mono<Indexable> submitLogConfiguration() { if (!diagnosticLogsToUpdate) { return Mono.just((Indexable) this); } return updateDiagnosticLogsConfig(diagnosticLogs.innerModel()) .map( siteLogsConfigInner -> { WebAppBaseImpl.this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this); return WebAppBaseImpl.this; }); } @Override public WebDeploymentImpl<FluentT, FluentImplT> deploy() { return new WebDeploymentImpl<>(this); } WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding( final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) { sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding); return this; } @SuppressWarnings("unchecked") public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) { for (String hostname : hostnames) { if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) { defineHostnameBinding() .withAzureManagedDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.A) .attach(); } else { defineHostnameBinding() .withAzureManagedDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) .attach(); } } return (FluentImplT) this; } @SuppressWarnings("unchecked") public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() { HostnameBindingInner inner = new HostnameBindingInner(); inner.withSiteName(name()); inner.withAzureResourceType(AzureResourceType.WEBSITE); inner.withAzureResourceName(name()); inner.withHostnameType(HostnameType.VERIFIED); return new HostnameBindingImpl<>(inner, (FluentImplT) this); } @SuppressWarnings("unchecked") public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) { for (String hostname : hostnames) { defineHostnameBinding() .withThirdPartyDomain(domain) .withSubDomain(hostname) .withDnsRecordType(CustomHostnameDnsRecordType.CNAME) .attach(); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutHostnameBinding(String hostname) { hostNameBindingsToDelete.add(hostname); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutSslBinding(String hostname) { if (hostNameSslStateMap.containsKey(hostname)) { hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true); } return (FluentImplT) this; } @SuppressWarnings("unchecked") FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) { this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppDisabledOnCreation() { innerModel().withEnabled(false); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) { innerModel().withScmSiteAlsoStopped(scmSiteAlsoStopped); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withClientAffinityEnabled(boolean enabled) { innerModel().withClientAffinityEnabled(enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withClientCertEnabled(boolean enabled) { innerModel().withClientCertEnabled(enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() { return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this); } @SuppressWarnings("unchecked") public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withNetFrameworkVersion(version.toString()); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withPhpVersion(PhpVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withPhpVersion(version.toString()); return (FluentImplT) this; } public FluentImplT withoutPhp() { return withPhpVersion(PhpVersion.fromString("")); } @SuppressWarnings("unchecked") public FluentImplT withJavaVersion(JavaVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withJavaVersion(version.toString()); return (FluentImplT) this; } public FluentImplT withoutJava() { return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString("")); } @SuppressWarnings("unchecked") public FluentImplT withWebContainer(WebContainer webContainer) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (webContainer == null) { siteConfig.withJavaContainer(null); siteConfig.withJavaContainerVersion(null); } else if (webContainer.toString().isEmpty()) { siteConfig.withJavaContainer(""); siteConfig.withJavaContainerVersion(""); } else { String[] containerInfo = webContainer.toString().split(" "); siteConfig.withJavaContainer(containerInfo[0]); siteConfig.withJavaContainerVersion(containerInfo[1]); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withPythonVersion(PythonVersion version) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withPythonVersion(version.toString()); return (FluentImplT) this; } public FluentImplT withoutPython() { return withPythonVersion(PythonVersion.fromString("")); } @SuppressWarnings("unchecked") public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86)); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withWebSocketsEnabled(boolean enabled) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withWebSocketsEnabled(enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withAlwaysOn(alwaysOn); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withManagedPipelineMode(managedPipelineMode); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAutoSwapSlotName(String slotName) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withAutoSwapSlotName(slotName); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withRemoteDebuggingEnabled(true); siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString()); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withRemoteDebuggingDisabled() { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withRemoteDebuggingEnabled(false); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withDefaultDocument(String document) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (siteConfig.defaultDocuments() == null) { siteConfig.withDefaultDocuments(new ArrayList<String>()); } siteConfig.defaultDocuments().add(document); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withDefaultDocuments(List<String> documents) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (siteConfig.defaultDocuments() == null) { siteConfig.withDefaultDocuments(new ArrayList<>()); } siteConfig.defaultDocuments().addAll(documents); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutDefaultDocument(String document) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } if (siteConfig.defaultDocuments() != null) { siteConfig.defaultDocuments().remove(document); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withHttpsOnly(boolean httpsOnly) { innerModel().withHttpsOnly(httpsOnly); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withHttp20Enabled(boolean http20Enabled) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withHttp20Enabled(http20Enabled); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withFtpsState(FtpsState ftpsState) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withFtpsState(ftpsState); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withVirtualApplications(virtualApplications); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withMinTlsVersion(minTlsVersion); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppSetting(String key, String value) { appSettingsToAdd.put(key, value); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppSettings(Map<String, String> settings) { appSettingsToAdd.putAll(settings); return (FluentImplT) this; } public FluentImplT withStickyAppSetting(String key, String value) { withAppSetting(key, value); return withAppSettingStickiness(key, true); } @SuppressWarnings("unchecked") public FluentImplT withStickyAppSettings(Map<String, String> settings) { withAppSettings(settings); for (String key : settings.keySet()) { appSettingStickiness.put(key, true); } return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutAppSetting(String key) { appSettingsToRemove.add(key); appSettingStickiness.remove(key); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withAppSettingStickiness(String key, boolean sticky) { appSettingStickiness.put(key, sticky); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) { connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type)); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) { connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type)); connectionStringStickiness.put(name, true); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutConnectionString(String name) { connectionStringsToRemove.add(name); connectionStringStickiness.remove(name); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) { connectionStringStickiness.put(name, stickiness); return (FluentImplT) this; } @SuppressWarnings("unchecked") void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) { this.sourceControl = sourceControl; } public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() { SiteSourceControlInner sourceControlInner = new SiteSourceControlInner(); return new WebAppSourceControlImpl<>(sourceControlInner, this); } @SuppressWarnings("unchecked") public FluentImplT withLocalGitSourceControl() { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withScmType(ScmType.LOCAL_GIT); return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withoutSourceControl() { sourceControlToDelete = true; return (FluentImplT) this; } @SuppressWarnings("unchecked") void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) { this.authentication = authentication; authenticationToUpdate = true; } void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) { this.diagnosticLogs = diagnosticLogs; diagnosticLogsToUpdate = true; } @Override @SuppressWarnings("unchecked") public Mono<FluentT> refreshAsync() { return super .refreshAsync() .flatMap( fluentT -> getConfigInner() .map( returnedSiteConfig -> { siteConfig = returnedSiteConfig; return fluentT; })); } @Override protected Mono<SiteInner> getInnerAsync() { return getInner(); } @Override public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() { return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this); } @Override @SuppressWarnings("unchecked") public FluentImplT withoutAuthentication() { this.authentication.innerModel().withEnabled(false); authenticationToUpdate = true; return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) { return updateDiagnosticLogsConfiguration() .withWebServerLogging() .withWebServerLogsStoredOnFileSystem() .withWebServerFileSystemQuotaInMB(quotaInMB) .withLogRetentionDays(retentionDays) .attach(); } @Override public FluentImplT withContainerLoggingEnabled() { return withContainerLoggingEnabled(35, 0); } @Override @SuppressWarnings("unchecked") public FluentImplT withContainerLoggingDisabled() { return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach(); } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedManagedServiceIdentity() { this.webAppMsiHandler.withLocalManagedServiceIdentity(); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withoutSystemAssignedManagedServiceIdentity() { this.webAppMsiHandler.withoutLocalManagedServiceIdentity(); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withUserAssignedManagedServiceIdentity() { return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) { this.webAppMsiHandler.withAccessTo(resourceId, role); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) { this.webAppMsiHandler.withAccessToCurrentResourceGroup(role); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) { this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) { this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) { this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) { this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) { this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId); return (FluentImplT) this; } @Override public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() { if (diagnosticLogs == null) { return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this); } else { return diagnosticLogs; } } @Override public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() { return defineDiagnosticLogsConfiguration(); } @Override public ManagedServiceIdentity identity() { return webSiteBase.identity(); } @Override public boolean hyperV() { return webSiteBase.hyperV(); } @Override public HostingEnvironmentProfile hostingEnvironmentProfile() { return webSiteBase.hostingEnvironmentProfile(); } @Override public Set<String> clientCertExclusionPaths() { return webSiteBase.clientCertExclusionPaths(); } @Override public Set<String> possibleOutboundIpAddresses() { return webSiteBase.possibleOutboundIpAddresses(); } @Override public int dailyMemoryTimeQuota() { return webSiteBase.dailyMemoryTimeQuota(); } @Override public OffsetDateTime suspendedTill() { return webSiteBase.suspendedTill(); } @Override public int maxNumberOfWorkers() { return webSiteBase.maxNumberOfWorkers(); } @Override public SlotSwapStatus slotSwapStatus() { return webSiteBase.slotSwapStatus(); } @Override public RedundancyMode redundancyMode() { return webSiteBase.redundancyMode(); } private static class PipedInputStreamWithCallback extends PipedInputStream { private Runnable callback; private void addCallback(Runnable action) { this.callback = action; } @Override public void close() throws IOException { callback.run(); super.close(); } } protected void setAppFrameworkVersion(String fxVersion) { if (operatingSystem() == OperatingSystem.LINUX) { siteConfig.withLinuxFxVersion(fxVersion); } else { siteConfig.withWindowsFxVersion(fxVersion); } } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessFromAllNetworks() { this.ensureIpSecurityRestrictions(); this.siteConfig.withIpSecurityRestrictions(new ArrayList<>()); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessFromNetworkSubnet(String subnetId, int priority) { this.ensureIpSecurityRestrictions(); this.siteConfig.ipSecurityRestrictions().add(new IpSecurityRestriction() .withAction(IP_RESTRICTION_ACTION_ALLOW) .withPriority(priority) .withTag(IpFilterTag.DEFAULT) .withVnetSubnetResourceId(subnetId)); return (FluentImplT) this; } @Override public FluentImplT withAccessFromIpAddress(String ipAddress, int priority) { String ipAddressCidr = ipAddress.contains("/") ? ipAddress : ipAddress + "/32"; return withAccessFromIpAddressRange(ipAddressCidr, priority); } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessFromIpAddressRange(String ipAddressCidr, int priority) { this.ensureIpSecurityRestrictions(); this.siteConfig.ipSecurityRestrictions().add(new IpSecurityRestriction() .withAction(IP_RESTRICTION_ACTION_ALLOW) .withPriority(priority) .withTag(IpFilterTag.DEFAULT) .withIpAddress(ipAddressCidr)); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withAccessRule(IpSecurityRestriction ipSecurityRule) { this.ensureIpSecurityRestrictions(); this.siteConfig.ipSecurityRestrictions().add(ipSecurityRule); return (FluentImplT) this; } @Override @SuppressWarnings("unchecked") public FluentImplT withoutNetworkSubnetAccess(String subnetId) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() .filter(r -> !(IP_RESTRICTION_ACTION_ALLOW.equalsIgnoreCase(r.action()) && IpFilterTag.DEFAULT == r.tag() && subnetId.equalsIgnoreCase(r.vnetSubnetResourceId()))) .collect(Collectors.toList()) ); } return (FluentImplT) this; } @Override public FluentImplT withoutIpAddressAccess(String ipAddress) { String ipAddressCidr = ipAddress.contains("/") ? ipAddress : ipAddress + "/32"; return withoutIpAddressRangeAccess(ipAddressCidr); } @Override @SuppressWarnings("unchecked") public FluentImplT withoutIpAddressRangeAccess(String ipAddressCidr) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() .filter(r -> !(IP_RESTRICTION_ACTION_ALLOW.equalsIgnoreCase(r.action()) && IpFilterTag.DEFAULT == r.tag() && Objects.equals(ipAddressCidr, r.ipAddress()))) .collect(Collectors.toList()) ); } return (FluentImplT) this; } @Override public Map<String, String> getSiteAppSettings() { return getSiteAppSettingsAsync().block(); } @Override public Mono<Map<String, String>> getSiteAppSettingsAsync() { return kuduClient.settings(); } @Override @SuppressWarnings("unchecked") public FluentImplT withoutAccessRule(IpSecurityRestriction ipSecurityRule) { if (this.siteConfig != null && this.siteConfig.ipSecurityRestrictions() != null) { this.siteConfig.withIpSecurityRestrictions(this.siteConfig.ipSecurityRestrictions().stream() .filter(r -> !(Objects.equals(r.action(), ipSecurityRule.action()) && Objects.equals(r.tag(), ipSecurityRule.tag()) && (Objects.equals(r.ipAddress(), ipSecurityRule.ipAddress()) || Objects.equals(r.vnetSubnetResourceId(), ipSecurityRule.vnetSubnetResourceId())))) .collect(Collectors.toList()) ); } return (FluentImplT) this; } private void ensureIpSecurityRestrictions() { if (this.siteConfig == null) { this.siteConfig = new SiteConfigResourceInner(); } if (this.siteConfig.ipSecurityRestrictions() == null) { this.siteConfig.withIpSecurityRestrictions(new ArrayList<>()); } } protected static final class PrivateLinkResourceImpl implements PrivateLinkResource { private final com.azure.resourcemanager.appservice.models.PrivateLinkResource innerModel; protected PrivateLinkResourceImpl(com.azure.resourcemanager.appservice.models.PrivateLinkResource innerModel) { this.innerModel = innerModel; } @Override public String groupId() { return innerModel.properties().groupId(); } @Override public List<String> requiredMemberNames() { return Collections.unmodifiableList(innerModel.properties().requiredMembers()); } @Override public List<String> requiredDnsZoneNames() { return Collections.unmodifiableList(innerModel.properties().requiredZoneNames()); } } protected static final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { private final RemotePrivateEndpointConnectionArmResourceInner innerModel; private final PrivateEndpoint privateEndpoint; private final com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState; private final PrivateEndpointConnectionProvisioningState provisioningState; protected PrivateEndpointConnectionImpl(RemotePrivateEndpointConnectionArmResourceInner innerModel) { this.innerModel = innerModel; this.privateEndpoint = innerModel.privateEndpoint() == null ? null : new PrivateEndpoint(innerModel.privateEndpoint().id()); this.privateLinkServiceConnectionState = innerModel.privateLinkServiceConnectionState() == null ? null : new com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState( innerModel.privateLinkServiceConnectionState().status() == null ? null : com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateEndpointServiceConnectionStatus .fromString(innerModel.privateLinkServiceConnectionState().status()), innerModel.privateLinkServiceConnectionState().description(), innerModel.privateLinkServiceConnectionState().actionsRequired()); this.provisioningState = innerModel.provisioningState() == null ? null : PrivateEndpointConnectionProvisioningState.fromString(innerModel.provisioningState()); } @Override public String id() { return innerModel.id(); } @Override public String name() { return innerModel.name(); } @Override public String type() { return innerModel.type(); } @Override public PrivateEndpoint privateEndpoint() { return privateEndpoint; } @Override public com.azure.resourcemanager.resources.fluentcore.arm.models.PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { return privateLinkServiceConnectionState; } @Override public PrivateEndpointConnectionProvisioningState provisioningState() { return provisioningState; } } }
will the builder throw exceptions when set null?
protected void configureProxy(T builder) { if (getAzureProperties().getProxy() == null) { return; } final ProxyOptions proxyOptions = proxyOptionsConverter.convert(getAzureProperties().getProxy()); if (proxyOptions != null) { consumeProxyOptions().accept(builder, proxyOptions); } else { LOGGER.warn("Invalid AMQP proxy configuration properties."); } }
consumeProxyOptions().accept(builder, proxyOptions);
protected void configureProxy(T builder) { if (getAzureProperties().getProxy() == null) { return; } final ProxyOptions proxyOptions = proxyOptionsConverter.convert(getAzureProperties().getProxy()); if (proxyOptions != null) { consumeProxyOptions().accept(builder, proxyOptions); } else { LOGGER.debug("No AMQP proxy properties available."); } }
class AbstractAzureAmqpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureAmqpClientBuilderFactory.class); private ClientOptions clientOptions = new ClientOptions(); private final AzureAmqpProxyOptionsConverter proxyOptionsConverter = new AzureAmqpProxyOptionsConverter(); private final AzureAmqpRetryOptionsConverter retryOptionsConverter = new AzureAmqpRetryOptionsConverter(); protected abstract BiConsumer<T, ProxyOptions> consumeProxyOptions(); protected abstract BiConsumer<T, AmqpTransportType> consumeAmqpTransportType(); protected abstract BiConsumer<T, AmqpRetryOptions> consumeAmqpRetryOptions(); protected abstract BiConsumer<T, ClientOptions> consumeClientOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureAmqpClient(builder); } protected void configureAmqpClient(T builder) { configureClientProperties(builder); configureAmqpTransportProperties(builder); } protected void configureAmqpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final AmqpClientProperties properties; if (clientProperties instanceof AmqpClientProperties) { properties = (AmqpClientProperties) clientProperties; consumeAmqpTransportType().accept(builder, properties.getTransportType()); } } protected void configureClientProperties(T builder) { consumeClientOptions().accept(builder, this.clientOptions); } @Override protected void configureApplicationId(T builder) { this.clientOptions.setApplicationId(getApplicationId()); } @Override protected void configureRetry(T builder) { final RetryProperties retry = getAzureProperties().getRetry(); if (retry == null) { return; } AmqpRetryOptions retryOptions = retryOptionsConverter.convert(retry); consumeAmqpRetryOptions().accept(builder, retryOptions); } @Override protected ClientOptions getClientOptions() { return clientOptions; } public void setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; } }
class AbstractAzureAmqpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureAmqpClientBuilderFactory.class); private ClientOptions clientOptions = new ClientOptions(); private final AzureAmqpProxyOptionsConverter proxyOptionsConverter = new AzureAmqpProxyOptionsConverter(); private final AzureAmqpRetryOptionsConverter retryOptionsConverter = new AzureAmqpRetryOptionsConverter(); protected abstract BiConsumer<T, ProxyOptions> consumeProxyOptions(); protected abstract BiConsumer<T, AmqpTransportType> consumeAmqpTransportType(); protected abstract BiConsumer<T, AmqpRetryOptions> consumeAmqpRetryOptions(); protected abstract BiConsumer<T, ClientOptions> consumeClientOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureAmqpClient(builder); } protected void configureAmqpClient(T builder) { configureClientProperties(builder); configureAmqpTransportProperties(builder); } protected void configureAmqpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final AmqpClientProperties properties; if (clientProperties instanceof AmqpClientProperties) { properties = (AmqpClientProperties) clientProperties; consumeAmqpTransportType().accept(builder, properties.getTransportType()); } } protected void configureClientProperties(T builder) { consumeClientOptions().accept(builder, this.clientOptions); } @Override protected void configureApplicationId(T builder) { this.clientOptions.setApplicationId(getApplicationId()); } @Override protected void configureRetry(T builder) { final RetryProperties retry = getAzureProperties().getRetry(); if (retry == null) { return; } AmqpRetryOptions retryOptions = retryOptionsConverter.convert(retry); consumeAmqpRetryOptions().accept(builder, retryOptions); } @Override protected ClientOptions getClientOptions() { return clientOptions; } public void setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; } }
The proxy converter will return null if no hostname is configured.
protected void configureProxy(T builder) { if (getAzureProperties().getProxy() == null) { return; } final ProxyOptions proxyOptions = proxyOptionsConverter.convert(getAzureProperties().getProxy()); if (proxyOptions != null) { consumeProxyOptions().accept(builder, proxyOptions); } else { LOGGER.warn("Invalid AMQP proxy configuration properties."); } }
consumeProxyOptions().accept(builder, proxyOptions);
protected void configureProxy(T builder) { if (getAzureProperties().getProxy() == null) { return; } final ProxyOptions proxyOptions = proxyOptionsConverter.convert(getAzureProperties().getProxy()); if (proxyOptions != null) { consumeProxyOptions().accept(builder, proxyOptions); } else { LOGGER.debug("No AMQP proxy properties available."); } }
class AbstractAzureAmqpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureAmqpClientBuilderFactory.class); private ClientOptions clientOptions = new ClientOptions(); private final AzureAmqpProxyOptionsConverter proxyOptionsConverter = new AzureAmqpProxyOptionsConverter(); private final AzureAmqpRetryOptionsConverter retryOptionsConverter = new AzureAmqpRetryOptionsConverter(); protected abstract BiConsumer<T, ProxyOptions> consumeProxyOptions(); protected abstract BiConsumer<T, AmqpTransportType> consumeAmqpTransportType(); protected abstract BiConsumer<T, AmqpRetryOptions> consumeAmqpRetryOptions(); protected abstract BiConsumer<T, ClientOptions> consumeClientOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureAmqpClient(builder); } protected void configureAmqpClient(T builder) { configureClientProperties(builder); configureAmqpTransportProperties(builder); } protected void configureAmqpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final AmqpClientProperties properties; if (clientProperties instanceof AmqpClientProperties) { properties = (AmqpClientProperties) clientProperties; consumeAmqpTransportType().accept(builder, properties.getTransportType()); } } protected void configureClientProperties(T builder) { consumeClientOptions().accept(builder, this.clientOptions); } @Override protected void configureApplicationId(T builder) { this.clientOptions.setApplicationId(getApplicationId()); } @Override protected void configureRetry(T builder) { final RetryProperties retry = getAzureProperties().getRetry(); if (retry == null) { return; } AmqpRetryOptions retryOptions = retryOptionsConverter.convert(retry); consumeAmqpRetryOptions().accept(builder, retryOptions); } @Override protected ClientOptions getClientOptions() { return clientOptions; } public void setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; } }
class AbstractAzureAmqpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureAmqpClientBuilderFactory.class); private ClientOptions clientOptions = new ClientOptions(); private final AzureAmqpProxyOptionsConverter proxyOptionsConverter = new AzureAmqpProxyOptionsConverter(); private final AzureAmqpRetryOptionsConverter retryOptionsConverter = new AzureAmqpRetryOptionsConverter(); protected abstract BiConsumer<T, ProxyOptions> consumeProxyOptions(); protected abstract BiConsumer<T, AmqpTransportType> consumeAmqpTransportType(); protected abstract BiConsumer<T, AmqpRetryOptions> consumeAmqpRetryOptions(); protected abstract BiConsumer<T, ClientOptions> consumeClientOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureAmqpClient(builder); } protected void configureAmqpClient(T builder) { configureClientProperties(builder); configureAmqpTransportProperties(builder); } protected void configureAmqpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final AmqpClientProperties properties; if (clientProperties instanceof AmqpClientProperties) { properties = (AmqpClientProperties) clientProperties; consumeAmqpTransportType().accept(builder, properties.getTransportType()); } } protected void configureClientProperties(T builder) { consumeClientOptions().accept(builder, this.clientOptions); } @Override protected void configureApplicationId(T builder) { this.clientOptions.setApplicationId(getApplicationId()); } @Override protected void configureRetry(T builder) { final RetryProperties retry = getAzureProperties().getRetry(); if (retry == null) { return; } AmqpRetryOptions retryOptions = retryOptionsConverter.convert(retry); consumeAmqpRetryOptions().accept(builder, retryOptions); } @Override protected ClientOptions getClientOptions() { return clientOptions; } public void setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; } }
Return null is okay for us right, we don't always require a proxy configuration.
protected void configureProxy(T builder) { if (getAzureProperties().getProxy() == null) { return; } final ProxyOptions proxyOptions = proxyOptionsConverter.convert(getAzureProperties().getProxy()); if (proxyOptions != null) { consumeProxyOptions().accept(builder, proxyOptions); } else { LOGGER.warn("Invalid AMQP proxy configuration properties."); } }
consumeProxyOptions().accept(builder, proxyOptions);
protected void configureProxy(T builder) { if (getAzureProperties().getProxy() == null) { return; } final ProxyOptions proxyOptions = proxyOptionsConverter.convert(getAzureProperties().getProxy()); if (proxyOptions != null) { consumeProxyOptions().accept(builder, proxyOptions); } else { LOGGER.debug("No AMQP proxy properties available."); } }
class AbstractAzureAmqpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureAmqpClientBuilderFactory.class); private ClientOptions clientOptions = new ClientOptions(); private final AzureAmqpProxyOptionsConverter proxyOptionsConverter = new AzureAmqpProxyOptionsConverter(); private final AzureAmqpRetryOptionsConverter retryOptionsConverter = new AzureAmqpRetryOptionsConverter(); protected abstract BiConsumer<T, ProxyOptions> consumeProxyOptions(); protected abstract BiConsumer<T, AmqpTransportType> consumeAmqpTransportType(); protected abstract BiConsumer<T, AmqpRetryOptions> consumeAmqpRetryOptions(); protected abstract BiConsumer<T, ClientOptions> consumeClientOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureAmqpClient(builder); } protected void configureAmqpClient(T builder) { configureClientProperties(builder); configureAmqpTransportProperties(builder); } protected void configureAmqpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final AmqpClientProperties properties; if (clientProperties instanceof AmqpClientProperties) { properties = (AmqpClientProperties) clientProperties; consumeAmqpTransportType().accept(builder, properties.getTransportType()); } } protected void configureClientProperties(T builder) { consumeClientOptions().accept(builder, this.clientOptions); } @Override protected void configureApplicationId(T builder) { this.clientOptions.setApplicationId(getApplicationId()); } @Override protected void configureRetry(T builder) { final RetryProperties retry = getAzureProperties().getRetry(); if (retry == null) { return; } AmqpRetryOptions retryOptions = retryOptionsConverter.convert(retry); consumeAmqpRetryOptions().accept(builder, retryOptions); } @Override protected ClientOptions getClientOptions() { return clientOptions; } public void setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; } }
class AbstractAzureAmqpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureAmqpClientBuilderFactory.class); private ClientOptions clientOptions = new ClientOptions(); private final AzureAmqpProxyOptionsConverter proxyOptionsConverter = new AzureAmqpProxyOptionsConverter(); private final AzureAmqpRetryOptionsConverter retryOptionsConverter = new AzureAmqpRetryOptionsConverter(); protected abstract BiConsumer<T, ProxyOptions> consumeProxyOptions(); protected abstract BiConsumer<T, AmqpTransportType> consumeAmqpTransportType(); protected abstract BiConsumer<T, AmqpRetryOptions> consumeAmqpRetryOptions(); protected abstract BiConsumer<T, ClientOptions> consumeClientOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureAmqpClient(builder); } protected void configureAmqpClient(T builder) { configureClientProperties(builder); configureAmqpTransportProperties(builder); } protected void configureAmqpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final AmqpClientProperties properties; if (clientProperties instanceof AmqpClientProperties) { properties = (AmqpClientProperties) clientProperties; consumeAmqpTransportType().accept(builder, properties.getTransportType()); } } protected void configureClientProperties(T builder) { consumeClientOptions().accept(builder, this.clientOptions); } @Override protected void configureApplicationId(T builder) { this.clientOptions.setApplicationId(getApplicationId()); } @Override protected void configureRetry(T builder) { final RetryProperties retry = getAzureProperties().getRetry(); if (retry == null) { return; } AmqpRetryOptions retryOptions = retryOptionsConverter.convert(retry); consumeAmqpRetryOptions().accept(builder, retryOptions); } @Override protected ClientOptions getClientOptions() { return clientOptions; } public void setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; } }
why not add if (ConnectionMode.GATEWAY.equals(this.cosmosProperties.getConnectionMode())) { } here
protected void configureService(CosmosClientBuilder builder) { PropertyMapper map = new PropertyMapper(); map.from(this.cosmosProperties.getEndpoint()).to(builder::endpoint); map.from(this.cosmosProperties.getConsistencyLevel()).to(builder::consistencyLevel); map.from(this.cosmosProperties.getClientTelemetryEnabled()).to(builder::clientTelemetryEnabled); map.from(this.cosmosProperties.getConnectionSharingAcrossClientsEnabled()).to(builder::connectionSharingAcrossClientsEnabled); map.from(this.cosmosProperties.getContentResponseOnWriteEnabled()).to(builder::contentResponseOnWriteEnabled); map.from(this.cosmosProperties.getEndpointDiscoveryEnabled()).to(builder::endpointDiscoveryEnabled); map.from(this.cosmosProperties.getMultipleWriteRegionsEnabled()).to(builder::multipleWriteRegionsEnabled); map.from(this.cosmosProperties.getReadRequestsFallbackEnabled()).to(builder::readRequestsFallbackEnabled); map.from(this.cosmosProperties.getSessionCapturingOverrideEnabled()).to(builder::sessionCapturingOverrideEnabled); map.from(this.cosmosProperties.getPreferredRegions()).whenNot(List::isEmpty).to(builder::preferredRegions); map.from(this.cosmosProperties.getThrottlingRetryOptions()).to(builder::throttlingRetryOptions); map.from(this.cosmosProperties.getResourceToken()).to(builder::resourceToken); map.from(this.cosmosProperties.getPermissions()).whenNot(List::isEmpty).to(builder::permissions); builder.gatewayMode(this.cosmosProperties.getGatewayConnection()); if (ConnectionMode.DIRECT.equals(this.cosmosProperties.getConnectionMode())) { builder.directMode(this.cosmosProperties.getDirectConnection()); } }
builder.gatewayMode(this.cosmosProperties.getGatewayConnection());
protected void configureService(CosmosClientBuilder builder) { PropertyMapper map = new PropertyMapper(); map.from(this.cosmosProperties.getEndpoint()).to(builder::endpoint); map.from(this.cosmosProperties.getConsistencyLevel()).to(builder::consistencyLevel); map.from(this.cosmosProperties.getClientTelemetryEnabled()).to(builder::clientTelemetryEnabled); map.from(this.cosmosProperties.getConnectionSharingAcrossClientsEnabled()).to(builder::connectionSharingAcrossClientsEnabled); map.from(this.cosmosProperties.getContentResponseOnWriteEnabled()).to(builder::contentResponseOnWriteEnabled); map.from(this.cosmosProperties.getEndpointDiscoveryEnabled()).to(builder::endpointDiscoveryEnabled); map.from(this.cosmosProperties.getMultipleWriteRegionsEnabled()).to(builder::multipleWriteRegionsEnabled); map.from(this.cosmosProperties.getReadRequestsFallbackEnabled()).to(builder::readRequestsFallbackEnabled); map.from(this.cosmosProperties.getSessionCapturingOverrideEnabled()).to(builder::sessionCapturingOverrideEnabled); map.from(this.cosmosProperties.getPreferredRegions()).whenNot(List::isEmpty).to(builder::preferredRegions); map.from(this.cosmosProperties.getThrottlingRetryOptions()).to(builder::throttlingRetryOptions); map.from(this.cosmosProperties.getResourceToken()).to(builder::resourceToken); map.from(this.cosmosProperties.getPermissions()).whenNot(List::isEmpty).to(builder::permissions); if (ConnectionMode.DIRECT.equals(this.cosmosProperties.getConnectionMode())) { builder.directMode(this.cosmosProperties.getDirectConnection(), this.cosmosProperties.getGatewayConnection()); } else if (ConnectionMode.GATEWAY.equals(this.cosmosProperties.getConnectionMode())) { builder.gatewayMode(this.cosmosProperties.getGatewayConnection()); } }
class CosmosClientBuilderFactory extends AbstractAzureServiceClientBuilderFactory<CosmosClientBuilder> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosClientBuilderFactory.class); private final CosmosProperties cosmosProperties; public CosmosClientBuilderFactory(CosmosProperties cosmosProperties) { this.cosmosProperties = cosmosProperties; } @Override protected CosmosClientBuilder createBuilderInstance() { return new CosmosClientBuilder(); } @Override protected AzureProperties getAzureProperties() { return this.cosmosProperties; } @Override protected List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(CosmosClientBuilder builder) { return Arrays.asList( new KeyAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())), new TokenAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())) ); } @Override protected void configureApplicationId(CosmosClientBuilder builder) { builder.userAgentSuffix(ApplicationId.AZURE_SPRING_COSMOS); } @Override protected void configureProxy(CosmosClientBuilder builder) { LOGGER.debug("No configureProxy for CosmosClientBuilder."); } @Override protected void configureRetry(CosmosClientBuilder builder) { LOGGER.debug("No configureRetry for CosmosClientBuilder."); } @Override @Override protected BiConsumer<CosmosClientBuilder, Configuration> consumeConfiguration() { LOGGER.warn("Configuration instance is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } @Override protected BiConsumer<CosmosClientBuilder, TokenCredential> consumeDefaultTokenCredential() { return CosmosClientBuilder::credential; } @Override protected BiConsumer<CosmosClientBuilder, String> consumeConnectionString() { LOGGER.debug("Connection string is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } }
class CosmosClientBuilderFactory extends AbstractAzureServiceClientBuilderFactory<CosmosClientBuilder> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosClientBuilderFactory.class); private final CosmosProperties cosmosProperties; public CosmosClientBuilderFactory(CosmosProperties cosmosProperties) { this.cosmosProperties = cosmosProperties; } @Override protected CosmosClientBuilder createBuilderInstance() { return new CosmosClientBuilder(); } @Override protected AzureProperties getAzureProperties() { return this.cosmosProperties; } @Override protected List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(CosmosClientBuilder builder) { return Arrays.asList( new KeyAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())), new TokenAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())) ); } @Override protected void configureApplicationId(CosmosClientBuilder builder) { builder.userAgentSuffix(ApplicationId.AZURE_SPRING_COSMOS); } @Override protected void configureProxy(CosmosClientBuilder builder) { LOGGER.debug("No configureProxy for CosmosClientBuilder."); } @Override protected void configureRetry(CosmosClientBuilder builder) { LOGGER.debug("No configureRetry for CosmosClientBuilder."); } @Override @Override protected BiConsumer<CosmosClientBuilder, Configuration> consumeConfiguration() { LOGGER.warn("Configuration instance is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } @Override protected BiConsumer<CosmosClientBuilder, TokenCredential> consumeDefaultTokenCredential() { return CosmosClientBuilder::credential; } @Override protected BiConsumer<CosmosClientBuilder, String> consumeConnectionString() { LOGGER.debug("Connection string is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } }
The direct mode will also use the proxy configuration which is from the gateconnection configuration, then the gateconnection will have the high priority to apply.
protected void configureService(CosmosClientBuilder builder) { PropertyMapper map = new PropertyMapper(); map.from(this.cosmosProperties.getEndpoint()).to(builder::endpoint); map.from(this.cosmosProperties.getConsistencyLevel()).to(builder::consistencyLevel); map.from(this.cosmosProperties.getClientTelemetryEnabled()).to(builder::clientTelemetryEnabled); map.from(this.cosmosProperties.getConnectionSharingAcrossClientsEnabled()).to(builder::connectionSharingAcrossClientsEnabled); map.from(this.cosmosProperties.getContentResponseOnWriteEnabled()).to(builder::contentResponseOnWriteEnabled); map.from(this.cosmosProperties.getEndpointDiscoveryEnabled()).to(builder::endpointDiscoveryEnabled); map.from(this.cosmosProperties.getMultipleWriteRegionsEnabled()).to(builder::multipleWriteRegionsEnabled); map.from(this.cosmosProperties.getReadRequestsFallbackEnabled()).to(builder::readRequestsFallbackEnabled); map.from(this.cosmosProperties.getSessionCapturingOverrideEnabled()).to(builder::sessionCapturingOverrideEnabled); map.from(this.cosmosProperties.getPreferredRegions()).whenNot(List::isEmpty).to(builder::preferredRegions); map.from(this.cosmosProperties.getThrottlingRetryOptions()).to(builder::throttlingRetryOptions); map.from(this.cosmosProperties.getResourceToken()).to(builder::resourceToken); map.from(this.cosmosProperties.getPermissions()).whenNot(List::isEmpty).to(builder::permissions); builder.gatewayMode(this.cosmosProperties.getGatewayConnection()); if (ConnectionMode.DIRECT.equals(this.cosmosProperties.getConnectionMode())) { builder.directMode(this.cosmosProperties.getDirectConnection()); } }
builder.gatewayMode(this.cosmosProperties.getGatewayConnection());
protected void configureService(CosmosClientBuilder builder) { PropertyMapper map = new PropertyMapper(); map.from(this.cosmosProperties.getEndpoint()).to(builder::endpoint); map.from(this.cosmosProperties.getConsistencyLevel()).to(builder::consistencyLevel); map.from(this.cosmosProperties.getClientTelemetryEnabled()).to(builder::clientTelemetryEnabled); map.from(this.cosmosProperties.getConnectionSharingAcrossClientsEnabled()).to(builder::connectionSharingAcrossClientsEnabled); map.from(this.cosmosProperties.getContentResponseOnWriteEnabled()).to(builder::contentResponseOnWriteEnabled); map.from(this.cosmosProperties.getEndpointDiscoveryEnabled()).to(builder::endpointDiscoveryEnabled); map.from(this.cosmosProperties.getMultipleWriteRegionsEnabled()).to(builder::multipleWriteRegionsEnabled); map.from(this.cosmosProperties.getReadRequestsFallbackEnabled()).to(builder::readRequestsFallbackEnabled); map.from(this.cosmosProperties.getSessionCapturingOverrideEnabled()).to(builder::sessionCapturingOverrideEnabled); map.from(this.cosmosProperties.getPreferredRegions()).whenNot(List::isEmpty).to(builder::preferredRegions); map.from(this.cosmosProperties.getThrottlingRetryOptions()).to(builder::throttlingRetryOptions); map.from(this.cosmosProperties.getResourceToken()).to(builder::resourceToken); map.from(this.cosmosProperties.getPermissions()).whenNot(List::isEmpty).to(builder::permissions); if (ConnectionMode.DIRECT.equals(this.cosmosProperties.getConnectionMode())) { builder.directMode(this.cosmosProperties.getDirectConnection(), this.cosmosProperties.getGatewayConnection()); } else if (ConnectionMode.GATEWAY.equals(this.cosmosProperties.getConnectionMode())) { builder.gatewayMode(this.cosmosProperties.getGatewayConnection()); } }
class CosmosClientBuilderFactory extends AbstractAzureServiceClientBuilderFactory<CosmosClientBuilder> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosClientBuilderFactory.class); private final CosmosProperties cosmosProperties; public CosmosClientBuilderFactory(CosmosProperties cosmosProperties) { this.cosmosProperties = cosmosProperties; } @Override protected CosmosClientBuilder createBuilderInstance() { return new CosmosClientBuilder(); } @Override protected AzureProperties getAzureProperties() { return this.cosmosProperties; } @Override protected List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(CosmosClientBuilder builder) { return Arrays.asList( new KeyAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())), new TokenAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())) ); } @Override protected void configureApplicationId(CosmosClientBuilder builder) { builder.userAgentSuffix(ApplicationId.AZURE_SPRING_COSMOS); } @Override protected void configureProxy(CosmosClientBuilder builder) { LOGGER.debug("No configureProxy for CosmosClientBuilder."); } @Override protected void configureRetry(CosmosClientBuilder builder) { LOGGER.debug("No configureRetry for CosmosClientBuilder."); } @Override @Override protected BiConsumer<CosmosClientBuilder, Configuration> consumeConfiguration() { LOGGER.warn("Configuration instance is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } @Override protected BiConsumer<CosmosClientBuilder, TokenCredential> consumeDefaultTokenCredential() { return CosmosClientBuilder::credential; } @Override protected BiConsumer<CosmosClientBuilder, String> consumeConnectionString() { LOGGER.debug("Connection string is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } }
class CosmosClientBuilderFactory extends AbstractAzureServiceClientBuilderFactory<CosmosClientBuilder> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosClientBuilderFactory.class); private final CosmosProperties cosmosProperties; public CosmosClientBuilderFactory(CosmosProperties cosmosProperties) { this.cosmosProperties = cosmosProperties; } @Override protected CosmosClientBuilder createBuilderInstance() { return new CosmosClientBuilder(); } @Override protected AzureProperties getAzureProperties() { return this.cosmosProperties; } @Override protected List<AuthenticationDescriptor<?>> getAuthenticationDescriptors(CosmosClientBuilder builder) { return Arrays.asList( new KeyAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())), new TokenAuthenticationDescriptor(provider -> builder.credential(provider.getCredential())) ); } @Override protected void configureApplicationId(CosmosClientBuilder builder) { builder.userAgentSuffix(ApplicationId.AZURE_SPRING_COSMOS); } @Override protected void configureProxy(CosmosClientBuilder builder) { LOGGER.debug("No configureProxy for CosmosClientBuilder."); } @Override protected void configureRetry(CosmosClientBuilder builder) { LOGGER.debug("No configureRetry for CosmosClientBuilder."); } @Override @Override protected BiConsumer<CosmosClientBuilder, Configuration> consumeConfiguration() { LOGGER.warn("Configuration instance is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } @Override protected BiConsumer<CosmosClientBuilder, TokenCredential> consumeDefaultTokenCredential() { return CosmosClientBuilder::credential; } @Override protected BiConsumer<CosmosClientBuilder, String> consumeConnectionString() { LOGGER.debug("Connection string is not supported to configure in CosmosClientBuilder"); return (a, b) -> { }; } }
Should we warn here if the proxy properties is not of type HttpProxyProperties?
protected void configureProxy(T builder) { final ProxyProperties proxyProperties = getAzureProperties().getProxy(); if (proxyProperties != null && proxyProperties instanceof HttpProxyProperties) { ProxyOptions proxyOptions = proxyOptionsConverter.convert((HttpProxyProperties) proxyProperties); if (proxyOptions != null) { this.httpClientOptions.setProxyOptions(proxyOptions); } else { LOGGER.debug("No HTTP proxy properties available."); } } }
if (proxyProperties != null && proxyProperties instanceof HttpProxyProperties) {
protected void configureProxy(T builder) { final ProxyProperties proxyProperties = getAzureProperties().getProxy(); if (proxyProperties == null) { return; } if (proxyProperties instanceof HttpProxyProperties) { ProxyOptions proxyOptions = proxyOptionsConverter.convert((HttpProxyProperties) proxyProperties); if (proxyOptions != null) { this.httpClientOptions.setProxyOptions(proxyOptions); } else { LOGGER.debug("No HTTP proxy properties available."); } } else { LOGGER.warn("Non-http proxy configuration will not be applied."); } }
class AbstractAzureHttpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureHttpClientBuilderFactory.class); private final HttpClientOptions httpClientOptions = new HttpClientOptions(); private HttpClientProvider httpClientProvider = new DefaultHttpProvider(); private final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); private HttpPipeline httpPipeline; private final AzureHttpProxyOptionsConverter proxyOptionsConverter = new AzureHttpProxyOptionsConverter(); private final AzureHttpLogOptionsConverter logOptionsConverter = new AzureHttpLogOptionsConverter(); protected abstract BiConsumer<T, HttpClient> consumeHttpClient(); protected abstract BiConsumer<T, HttpPipelinePolicy> consumeHttpPipelinePolicy(); protected abstract BiConsumer<T, HttpPipeline> consumeHttpPipeline(); protected abstract BiConsumer<T, HttpLogOptions> consumeHttpLogOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureHttpClient(builder); configureHttpLogOptions(builder); } protected void configureHttpClient(T builder) { if (this.httpPipeline != null) { consumeHttpPipeline().accept(builder, this.httpPipeline); } else { configureHttpHeaders(builder); configureHttpTransportProperties(builder); configureHttpPipelinePolicies(builder); final HttpClient httpClient = getHttpClientProvider().createInstance(this.httpClientOptions); consumeHttpClient().accept(builder, httpClient); } } @Override @Override protected void configureApplicationId(T builder) { this.httpClientOptions.setApplicationId(getApplicationId()); } protected void configureHttpHeaders(T builder) { this.httpClientOptions.setHeaders(getHeaders()); } protected void configureHttpLogOptions(T builder) { ClientProperties client = getAzureProperties().getClient(); HttpLogOptions logOptions = this.logOptionsConverter.convert(client.getLogging()); consumeHttpLogOptions().accept(builder, logOptions); } protected void configureHttpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final HttpClientProperties properties; if (clientProperties instanceof HttpClientProperties) { properties = (HttpClientProperties) clientProperties; httpClientOptions.setWriteTimeout(properties.getWriteTimeout()); httpClientOptions.responseTimeout(properties.getResponseTimeout()); httpClientOptions.readTimeout(properties.getReadTimeout()); } } @Override protected void configureRetry(T builder) { } protected void configureHttpPipelinePolicies(T builder) { for (HttpPipelinePolicy policy : this.httpPipelinePolicies) { consumeHttpPipelinePolicy().accept(builder, policy); } } protected List<Header> getHeaders() { final ClientProperties client = getAzureProperties().getClient(); if (client == null || client.getHeaders() == null) { return null; } return client.getHeaders() .stream() .map(h -> new Header(h.getName(), h.getValues())) .collect(Collectors.toList()); } public void setHttpClientProvider(HttpClientProvider httpClientProvider) { if (httpClientProvider != null) { this.httpClientProvider = httpClientProvider; } } protected List<HttpPipelinePolicy> getHttpPipelinePolicies() { return Collections.unmodifiableList(this.httpPipelinePolicies); } public void addHttpPipelinePolicy(HttpPipelinePolicy policy) { this.httpPipelinePolicies.add(policy); } public void setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; } protected HttpClientProvider getHttpClientProvider() { return this.httpClientProvider; } }
class AbstractAzureHttpClientBuilderFactory<T> extends AbstractAzureServiceClientBuilderFactory<T> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAzureHttpClientBuilderFactory.class); private final HttpClientOptions httpClientOptions = new HttpClientOptions(); private HttpClientProvider httpClientProvider = new DefaultHttpProvider(); private final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>(); private HttpPipeline httpPipeline; private final AzureHttpProxyOptionsConverter proxyOptionsConverter = new AzureHttpProxyOptionsConverter(); private final AzureHttpLogOptionsConverter logOptionsConverter = new AzureHttpLogOptionsConverter(); protected abstract BiConsumer<T, HttpClient> consumeHttpClient(); protected abstract BiConsumer<T, HttpPipelinePolicy> consumeHttpPipelinePolicy(); protected abstract BiConsumer<T, HttpPipeline> consumeHttpPipeline(); protected abstract BiConsumer<T, HttpLogOptions> consumeHttpLogOptions(); @Override protected void configureCore(T builder) { super.configureCore(builder); configureHttpClient(builder); configureHttpLogOptions(builder); } protected void configureHttpClient(T builder) { if (this.httpPipeline != null) { consumeHttpPipeline().accept(builder, this.httpPipeline); } else { configureHttpHeaders(builder); configureHttpTransportProperties(builder); configureHttpPipelinePolicies(builder); final HttpClient httpClient = getHttpClientProvider().createInstance(this.httpClientOptions); consumeHttpClient().accept(builder, httpClient); } } @Override @Override protected void configureApplicationId(T builder) { this.httpClientOptions.setApplicationId(getApplicationId()); } protected void configureHttpHeaders(T builder) { this.httpClientOptions.setHeaders(getHeaders()); } protected void configureHttpLogOptions(T builder) { ClientProperties client = getAzureProperties().getClient(); HttpLogOptions logOptions = this.logOptionsConverter.convert(client.getLogging()); consumeHttpLogOptions().accept(builder, logOptions); } protected void configureHttpTransportProperties(T builder) { final ClientProperties clientProperties = getAzureProperties().getClient(); if (clientProperties == null) { return; } final HttpClientProperties properties; if (clientProperties instanceof HttpClientProperties) { properties = (HttpClientProperties) clientProperties; httpClientOptions.setWriteTimeout(properties.getWriteTimeout()); httpClientOptions.responseTimeout(properties.getResponseTimeout()); httpClientOptions.readTimeout(properties.getReadTimeout()); } } @Override protected void configureRetry(T builder) { } protected void configureHttpPipelinePolicies(T builder) { for (HttpPipelinePolicy policy : this.httpPipelinePolicies) { consumeHttpPipelinePolicy().accept(builder, policy); } } protected List<Header> getHeaders() { final ClientProperties client = getAzureProperties().getClient(); if (client == null || client.getHeaders() == null) { return null; } return client.getHeaders() .stream() .map(h -> new Header(h.getName(), h.getValues())) .collect(Collectors.toList()); } public void setHttpClientProvider(HttpClientProvider httpClientProvider) { if (httpClientProvider != null) { this.httpClientProvider = httpClientProvider; } } protected List<HttpPipelinePolicy> getHttpPipelinePolicies() { return Collections.unmodifiableList(this.httpPipelinePolicies); } public void addHttpPipelinePolicy(HttpPipelinePolicy policy) { this.httpPipelinePolicies.add(policy); } public void setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; } protected HttpClientProvider getHttpClientProvider() { return this.httpClientProvider; } }
I believe this means "any new versions of the key will expire 6 months after creation", rather than "the policy will expire 6 months after it was created"
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions("MyRsaKey").setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey("MyRsaKey"); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy("MyRsaKey", keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); }
.setExpiryTime("P6M");
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "MyKey"; KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
```suggestion // An object containing the details of the recently updated key rotation policy will be returned by the update method. ```
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions("MyRsaKey").setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey("MyRsaKey"); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy("MyRsaKey", keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); }
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "MyKey"; KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
Consider doing this at the end, the sample should focus on managing a key rotation policy with being able to rotate a key on-demand as secondary. Not because rotating a key is secondary, but because it's a very simple API
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions("MyRsaKey").setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey("MyRsaKey"); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy("MyRsaKey", keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); }
KeyVaultKey manuallyRotatedKey = keyClient.rotateKey("MyRsaKey");
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "MyKey"; KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
This isn't quite right. They _do_ have a default policy set that will notify 30 days before expiry - it's just that the service is not returning this data yet (but it will). You could leave that last sentence out (I did in JS) and then update them whenever this change gets deployed
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions("MyRsaKey").setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey("MyRsaKey"); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy("MyRsaKey", keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); }
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "MyKey"; KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
Consider moving `MyRsaKey` to a variable / const - to give it a clearer name. like `keyName`. You can then use it in the other methods...
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions("MyRsaKey").setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey("MyRsaKey"); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy("MyRsaKey", keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); }
KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions("MyRsaKey").setKeySize(2048));
public static void main(String[] args) { KeyClient keyClient = new KeyClientBuilder() .vaultUrl("https: .credential(new DefaultAzureCredentialBuilder().build()) .buildClient(); String keyName = "MyKey"; KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); List<KeyRotationLifetimeAction> keyRotationLifetimeActionList = new ArrayList<>(); KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) .setTimeAfterCreate("P90D"); keyRotationLifetimeActionList.add(rotateLifetimeAction); KeyRotationPolicyProperties keyRotationPolicyProperties = new KeyRotationPolicyProperties() .setLifetimeActions(keyRotationLifetimeActionList) .setExpiryTime("P6M"); KeyRotationPolicy keyRotationPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties); System.out.printf("Updated key rotation policy with id: %s%n", keyRotationPolicy.getId()); KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
class KeyRotation { /** * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to * create a new key version. * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when an invalid key vault endpoint is passed. */ }
Nit: I don't have any problem with this and wrestled with it myself. While I do verify the default contains a "notify" action, I didn't very the days lest we tightly couple, but may also serve as a warning that something unexpectedly changed.
public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(client.getKeyRotationPolicy(keyName)) .assertNext(keyRotationPolicy -> { assertNotNull(keyRotationPolicy); assertNull(keyRotationPolicy.getId()); assertNull(keyRotationPolicy.getCreatedOn()); assertNull(keyRotationPolicy.getUpdatedOn()); assertNull(keyRotationPolicy.getExpiryTime()); assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getType()); assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); }) .verifyComplete(); }
assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry());
public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(client.getKeyRotationPolicy(keyName)) .assertNext(keyRotationPolicy -> { assertNotNull(keyRotationPolicy); assertNull(keyRotationPolicy.getId()); assertNull(keyRotationPolicy.getCreatedOn()); assertNull(keyRotationPolicy.getUpdatedOn()); assertNull(keyRotationPolicy.getExpiryTime()); assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getType()); assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); }) .verifyComplete(); }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); final KeyType keyType; if (runManagedHsmTest) { keyType = KeyType.RSA_HSM; } else { keyType = KeyType.RSA; } StepVerifier.create(client.createKey("", keyType)).verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((createKeyOptions, updateKeyOptions) -> { StepVerifier.create(client.createKey(createKeyOptions) .flatMap(createdKey -> { assertKeyEquals(createKeyOptions, createdKey); return client.updateKeyProperties(createdKey.getProperties() .setExpiresOn(updateKeyOptions.getExpiresOn())); })) .assertNext(updatedKey -> assertKeyEquals(updateKeyOptions, updatedKey)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((createKeyOptions, updateKeyOptions) -> { StepVerifier.create(client.createKey(createKeyOptions) .flatMap(createdKey -> { assertKeyEquals(createKeyOptions, createdKey); return client.updateKeyProperties(createdKey.getProperties() .setExpiresOn(updateKeyOptions.getExpiresOn())); })) .assertNext(updatedKey -> assertKeyEquals(updateKeyOptions, updatedKey)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(runManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicyProperties) -> { StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(client.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), client.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicyProperties) -> { StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(client.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), client.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that a key can be rotated. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName)) .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), client.rotateKey(keyName)))) .assertNext(tuple -> { KeyVaultKey createdKey = tuple.getT1(); KeyVaultKey rotatedKey = tuple.getT2(); assertEquals(createdKey.getName(), rotatedKey.getName()); assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); }) .verifyComplete(); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests * that cryptographic operations can be performed with said cryptography client. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((createKeyOptions) -> { StepVerifier.create(client.createKey(createKeyOptions)) .assertNext(response -> assertKeyEquals(createKeyOptions, response)) .verifyComplete(); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient(createKeyOptions.getName()); assertNotNull(cryptographyAsyncClient); byte[] plaintext = "myPlaintext".getBytes(); StepVerifier.create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) .map(EncryptResult::getCipherText) .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) .map(DecryptResult::getPlainText))) .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) .verifyComplete(); }); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a * {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey", ""); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey", null); assertNotNull(cryptographyAsyncClient); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKey(keyName).block(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; continue; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); final KeyType keyType; if (runManagedHsmTest) { keyType = KeyType.RSA_HSM; } else { keyType = KeyType.RSA; } StepVerifier.create(client.createKey("", keyType)).verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((createKeyOptions, updateKeyOptions) -> { StepVerifier.create(client.createKey(createKeyOptions) .flatMap(createdKey -> { assertKeyEquals(createKeyOptions, createdKey); return client.updateKeyProperties(createdKey.getProperties() .setExpiresOn(updateKeyOptions.getExpiresOn())); })) .assertNext(updatedKey -> assertKeyEquals(updateKeyOptions, updatedKey)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((createKeyOptions, updateKeyOptions) -> { StepVerifier.create(client.createKey(createKeyOptions) .flatMap(createdKey -> { assertKeyEquals(createKeyOptions, createdKey); return client.updateKeyProperties(createdKey.getProperties() .setExpiresOn(updateKeyOptions.getExpiresOn())); })) .assertNext(updatedKey -> assertKeyEquals(updateKeyOptions, updatedKey)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(runManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicyProperties) -> { StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(client.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), client.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicyProperties) -> { StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(client.updateKeyRotationPolicy(keyName, keyRotationPolicyProperties) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), client.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that a key can be rotated. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(client.createRsaKey(new CreateRsaKeyOptions(keyName)) .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), client.rotateKey(keyName)))) .assertNext(tuple -> { KeyVaultKey createdKey = tuple.getT1(); KeyVaultKey rotatedKey = tuple.getT2(); assertEquals(createdKey.getName(), rotatedKey.getName()); assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); }) .verifyComplete(); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests * that cryptographic operations can be performed with said cryptography client. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((createKeyOptions) -> { StepVerifier.create(client.createKey(createKeyOptions)) .assertNext(response -> assertKeyEquals(createKeyOptions, response)) .verifyComplete(); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient(createKeyOptions.getName()); assertNotNull(cryptographyAsyncClient); byte[] plaintext = "myPlaintext".getBytes(); StepVerifier.create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) .map(EncryptResult::getCipherText) .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) .map(DecryptResult::getPlainText))) .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) .verifyComplete(); }); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a * {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey", ""); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = client.getCryptographyAsyncClient("myKey", null); assertNotNull(cryptographyAsyncClient); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKey(keyName).block(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; continue; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
```suggestion Context traceContext = new Context(PARENT_TRACE_CONTEXT_KEY, "<user-current-context>"); ```
public void endTracingSpan() { String openTelemetrySpanKey = "openTelemetry-span"; Context traceContext = new Context(PARENT_TRACE_CONTEXT_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); }
Context traceContext = new Context(PARENT_TRACE_CONTEXT_KEY, "<user-current-span>");
public void endTracingSpan() { String openTelemetrySpanKey = "openTelemetry-span"; Context traceContext = new Context(PARENT_TRACE_CONTEXT_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ public void startTracingSpan() { Context traceContext = tracer.start("keyvault.setsecret", Context.NONE); System.out.printf("OpenTelemetry Context with started `keyvault.setsecret` span: %s%n", traceContext.getData(PARENT_TRACE_CONTEXT_KEY).get()); StartSpanOptions options = new StartSpanOptions(SpanKind.CLIENT) .setAttribute("key", "value"); Context updatedClientSpanContext = tracer.start("keyvault.setsecret", options, traceContext); System.out.printf("OpenTelemetry Context with started `keyvault.setsecret` span: %s%n", updatedClientSpanContext.getData(PARENT_TRACE_CONTEXT_KEY).get()); Context sendContext = new Context(ENTITY_PATH_KEY, "entity-path").addData(HOST_NAME_KEY, "hostname"); Context updatedSendContext = tracer.start("eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("OpenTelemetry Context with started `eventhubs.send` span: %s%n", updatedSendContext.getData(PARENT_TRACE_CONTEXT_KEY).get()); String diagnosticIdKey = "Diagnostic-Id"; Context updatedReceiveContext = tracer.start("EventHubs.receive", traceContext, ProcessKind.MESSAGE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(diagnosticIdKey).get().toString()); String spanImplContext = "span-context"; Context processContext = new Context(PARENT_TRACE_CONTEXT_KEY, "<OpenTelemetry-context>") .addData(spanImplContext, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("EventHubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); } /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void setSpanName() { Context contextWithName = tracer.setSpanName("keyvault.setsecret", Context.NONE); Context traceContext = tracer.start("placeholder", contextWithName); System.out.printf("OpenTelemetry Context with started `keyvault.setsecret` span: %s%n", traceContext.getData(PARENT_TRACE_CONTEXT_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context spanContext = tracer.start("test.method", Context.NONE, ProcessKind.MESSAGE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { String spanImplContext = "span-context"; Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(spanImplContext).get()); } /** * Code snippet for {@link Tracer */ @SuppressWarnings("try") public void makeSpanCurrent() { Context traceContext = tracer.start("EventHubs.process", Context.NONE); try (AutoCloseable ignored = tracer.makeSpanCurrent(traceContext)) { System.out.println("doing some work..."); } catch (Throwable throwable) { tracer.end("Failure", throwable, traceContext); } finally { tracer.end("OK", null, traceContext); } } /** * Code snippet for {@link Tracer */ public void getSharedSpanBuilder() { Context spanContext = tracer.getSharedSpanBuilder("message-span", Context.NONE); System.out.printf("Builder of current span being built: %s%n", spanContext.getData(SPAN_BUILDER_KEY).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } @Override public Context getSharedSpanBuilder(String spanName, Context context) { return null; } } }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ public void startTracingSpan() { Context traceContext = tracer.start("keyvault.setsecret", Context.NONE); System.out.printf("OpenTelemetry Context with started `keyvault.setsecret` span: %s%n", traceContext.getData(PARENT_TRACE_CONTEXT_KEY).get()); StartSpanOptions options = new StartSpanOptions(SpanKind.CLIENT) .setAttribute("key", "value"); Context updatedClientSpanContext = tracer.start("keyvault.setsecret", options, traceContext); System.out.printf("OpenTelemetry Context with started `keyvault.setsecret` span: %s%n", updatedClientSpanContext.getData(PARENT_TRACE_CONTEXT_KEY).get()); Context sendContext = new Context(ENTITY_PATH_KEY, "entity-path").addData(HOST_NAME_KEY, "hostname"); Context updatedSendContext = tracer.start("eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("OpenTelemetry Context with started `eventhubs.send` span: %s%n", updatedSendContext.getData(PARENT_TRACE_CONTEXT_KEY).get()); String diagnosticIdKey = "Diagnostic-Id"; Context updatedReceiveContext = tracer.start("EventHubs.receive", traceContext, ProcessKind.MESSAGE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(diagnosticIdKey).get().toString()); String spanImplContext = "span-context"; Context processContext = new Context(PARENT_TRACE_CONTEXT_KEY, "<OpenTelemetry-context>") .addData(spanImplContext, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("EventHubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); } /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void setSpanName() { Context contextWithName = tracer.setSpanName("keyvault.setsecret", Context.NONE); Context traceContext = tracer.start("placeholder", contextWithName); System.out.printf("OpenTelemetry Context with started `keyvault.setsecret` span: %s%n", traceContext.getData(PARENT_TRACE_CONTEXT_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context spanContext = tracer.start("test.method", Context.NONE, ProcessKind.MESSAGE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { String spanImplContext = "span-context"; Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(spanImplContext).get()); } /** * Code snippet for {@link Tracer */ @SuppressWarnings("try") public void makeSpanCurrent() { Context traceContext = tracer.start("EventHubs.process", Context.NONE); try (AutoCloseable ignored = tracer.makeSpanCurrent(traceContext)) { System.out.println("doing some work..."); } catch (Throwable throwable) { tracer.end("Failure", throwable, traceContext); } finally { tracer.end("OK", null, traceContext); } } /** * Code snippet for {@link Tracer */ public void getSharedSpanBuilder() { Context spanContext = tracer.getSharedSpanBuilder("message-span", Context.NONE); System.out.printf("Builder of current span being built: %s%n", spanContext.getData(SPAN_BUILDER_KEY).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } @Override public Context getSharedSpanBuilder(String spanName, Context context) { return null; } } }
nit: There are constants for these in Configuration
private TokenCredential getCredential() { return new ClientSecretCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("AZURE_CLIENT_ID")) .clientSecret(Configuration.getGlobalConfiguration().get("AZURE_CLIENT_SECRET")) .tenantId(Configuration.getGlobalConfiguration().get("AZURE_TENANT_ID")) .build(); }
.clientSecret(Configuration.getGlobalConfiguration().get("AZURE_CLIENT_SECRET"))
private 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(); }
class LogsQueryClientTest extends TestBase { public static final String WORKSPACE_ID = Configuration.getGlobalConfiguration() .get("AZURE_MONITOR_LOGS_WORKSPACE_ID", "d2d0e126-fa1e-4b0a-b647-250cdd471e68"); private LogsQueryClient client; public static final String QUERY_STRING = "let dt = datatable (DateTime: datetime, Bool:bool, Guid: guid, Int: int, Long:long, Double: double, String: string, Timespan: timespan, Decimal: decimal, Dynamic: dynamic)\n" + "[datetime(2015-12-31 23:59:59.9), false, guid(74be27de-1e4e-49d9-b579-fe0b331d3642), 12345, 1, 12345.6789, 'string value', 10s, decimal(0.10101), dynamic({\"a\":123, \"b\":\"hello\", \"c\":[1,2,3], \"d\":{}})];" + "range x from 1 to 100 step 1 | extend y=1 | join kind=fullouter dt on $left.y == $right.Long"; @BeforeEach public void setup() { LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder() .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.client = clientBuilder .buildClient(); } @Test public void testLogsQuery() { LogsQueryResult queryResults = client.queryWorkspace(WORKSPACE_ID, QUERY_STRING, new QueryTimeInterval(OffsetDateTime.of(LocalDateTime.of(2021, 01, 01, 0, 0), ZoneOffset.UTC), OffsetDateTime.of(LocalDateTime.of(2021, 06, 10, 0, 0), ZoneOffset.UTC))); assertEquals(1, queryResults.getAllTables().size()); assertEquals(1200, queryResults.getAllTables().get(0).getAllTableCells().size()); assertEquals(100, queryResults.getAllTables().get(0).getRows().size()); } @Test public void testLogsQueryBatch() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + "| take 3", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(1, responses.get(0).getAllTables().size()); assertEquals(24, responses.get(0).getAllTables().get(0).getAllTableCells().size()); assertEquals(2, responses.get(0).getAllTables().get(0).getRows().size()); assertEquals(1, responses.get(1).getAllTables().size()); assertEquals(36, responses.get(1).getAllTables().get(0).getAllTableCells().size()); assertEquals(3, responses.get(1).getAllTables().get(0).getRows().size()); } @Test @DisabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "LIVE", disabledReason = "multi-workspace " + "queries require sending logs to Azure Monitor first. So, run this test in playback or record mode only.") public void testMultipleWorkspaces() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, "union * | where TimeGenerated > ago(100d) | project TenantId | summarize count() by TenantId", null, new LogsQueryOptions() .setAdditionalWorkspaces(Arrays.asList("9dad0092-fd13-403a-b367-a189a090a541")), Context.NONE) .getValue(); assertEquals(1, queryResults.getAllTables().size()); assertEquals(2, queryResults .getAllTables() .get(0) .getRows() .stream() .map(row -> { System.out.println(row.getColumnValue("TenantId").get().getValueAsString()); return row.getColumnValue("TenantId").get(); }) .distinct() .count()); } @Test public void testBatchQueryPartialSuccess() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertEquals(LogsQueryResultStatus.FAILURE, responses.get(1).getQueryResultStatus()); assertNotNull(responses.get(1).getError()); assertEquals("BadArgumentError", responses.get(1).getError().getCode()); } @Test public void testStatistics() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true), Context.NONE).getValue(); assertEquals(1, queryResults.getAllTables().size()); assertNotNull(queryResults.getStatistics()); } @Test public void testBatchStatistics() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true)); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertNull(responses.get(0).getStatistics()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(1).getQueryResultStatus()); assertNull(responses.get(1).getError()); assertNotNull(responses.get(1).getStatistics()); } @Test public void testServerTimeout() { Random random = new Random(); while (true) { long count = 1000000000000L + random.nextInt(10000); try { client.queryWorkspaceWithResponse(WORKSPACE_ID, "range x from 1 to " + count + " step 1 | count", null, new LogsQueryOptions() .setServerTimeout(Duration.ofSeconds(5)), Context.NONE); } catch (Exception exception) { if (exception instanceof HttpResponseException) { HttpResponseException logsQueryException = (HttpResponseException) exception; if (logsQueryException.getResponse().getStatusCode() == 504) { break; } } } } } }
class LogsQueryClientTest extends TestBase { public static final String WORKSPACE_ID = Configuration.getGlobalConfiguration() .get("AZURE_MONITOR_LOGS_WORKSPACE_ID", "d2d0e126-fa1e-4b0a-b647-250cdd471e68"); private LogsQueryClient client; public static final String QUERY_STRING = "let dt = datatable (DateTime: datetime, Bool:bool, Guid: guid, Int: int, Long:long, Double: double, String: string, Timespan: timespan, Decimal: decimal, Dynamic: dynamic)\n" + "[datetime(2015-12-31 23:59:59.9), false, guid(74be27de-1e4e-49d9-b579-fe0b331d3642), 12345, 1, 12345.6789, 'string value', 10s, decimal(0.10101), dynamic({\"a\":123, \"b\":\"hello\", \"c\":[1,2,3], \"d\":{}})];" + "range x from 1 to 100 step 1 | extend y=1 | join kind=fullouter dt on $left.y == $right.Long"; @BeforeEach public void setup() { LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder() .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.client = clientBuilder .buildClient(); } @Test public void testLogsQuery() { LogsQueryResult queryResults = client.queryWorkspace(WORKSPACE_ID, QUERY_STRING, new QueryTimeInterval(OffsetDateTime.of(LocalDateTime.of(2021, 01, 01, 0, 0), ZoneOffset.UTC), OffsetDateTime.of(LocalDateTime.of(2021, 06, 10, 0, 0), ZoneOffset.UTC))); assertEquals(1, queryResults.getAllTables().size()); assertEquals(1200, queryResults.getAllTables().get(0).getAllTableCells().size()); assertEquals(100, queryResults.getAllTables().get(0).getRows().size()); } @Test public void testLogsQueryBatch() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + "| take 3", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(1, responses.get(0).getAllTables().size()); assertEquals(24, responses.get(0).getAllTables().get(0).getAllTableCells().size()); assertEquals(2, responses.get(0).getAllTables().get(0).getRows().size()); assertEquals(1, responses.get(1).getAllTables().size()); assertEquals(36, responses.get(1).getAllTables().get(0).getAllTableCells().size()); assertEquals(3, responses.get(1).getAllTables().get(0).getRows().size()); } @Test @DisabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "LIVE", disabledReason = "multi-workspace " + "queries require sending logs to Azure Monitor first. So, run this test in playback or record mode only.") public void testMultipleWorkspaces() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, "union * | where TimeGenerated > ago(100d) | project TenantId | summarize count() by TenantId", null, new LogsQueryOptions() .setAdditionalWorkspaces(Arrays.asList("9dad0092-fd13-403a-b367-a189a090a541")), Context.NONE) .getValue(); assertEquals(1, queryResults.getAllTables().size()); assertEquals(2, queryResults .getAllTables() .get(0) .getRows() .stream() .map(row -> { System.out.println(row.getColumnValue("TenantId").get().getValueAsString()); return row.getColumnValue("TenantId").get(); }) .distinct() .count()); } @Test public void testBatchQueryPartialSuccess() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertEquals(LogsQueryResultStatus.FAILURE, responses.get(1).getQueryResultStatus()); assertNotNull(responses.get(1).getError()); assertEquals("BadArgumentError", responses.get(1).getError().getCode()); } @Test public void testStatistics() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true), Context.NONE).getValue(); assertEquals(1, queryResults.getAllTables().size()); assertNotNull(queryResults.getStatistics()); } @Test public void testBatchStatistics() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true)); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertNull(responses.get(0).getStatistics()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(1).getQueryResultStatus()); assertNull(responses.get(1).getError()); assertNotNull(responses.get(1).getStatistics()); } @Test public void testServerTimeout() { Random random = new Random(); while (true) { long count = 1000000000000L + random.nextInt(10000); try { client.queryWorkspaceWithResponse(WORKSPACE_ID, "range x from 1 to " + count + " step 1 | count", null, new LogsQueryOptions() .setServerTimeout(Duration.ofSeconds(5)), Context.NONE); } catch (Exception exception) { if (exception instanceof HttpResponseException) { HttpResponseException logsQueryException = (HttpResponseException) exception; if (logsQueryException.getResponse().getStatusCode() == 504) { break; } } } } } }
> Mind adding a PR description for why were changing the structure of this SDK group to be different than normal Yes sorry. I just moved this from draft to PR and forgot it wasn't done already.
private TokenCredential getCredential() { return new ClientSecretCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("AZURE_CLIENT_ID")) .clientSecret(Configuration.getGlobalConfiguration().get("AZURE_CLIENT_SECRET")) .tenantId(Configuration.getGlobalConfiguration().get("AZURE_TENANT_ID")) .build(); }
.clientSecret(Configuration.getGlobalConfiguration().get("AZURE_CLIENT_SECRET"))
private 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(); }
class LogsQueryClientTest extends TestBase { public static final String WORKSPACE_ID = Configuration.getGlobalConfiguration() .get("AZURE_MONITOR_LOGS_WORKSPACE_ID", "d2d0e126-fa1e-4b0a-b647-250cdd471e68"); private LogsQueryClient client; public static final String QUERY_STRING = "let dt = datatable (DateTime: datetime, Bool:bool, Guid: guid, Int: int, Long:long, Double: double, String: string, Timespan: timespan, Decimal: decimal, Dynamic: dynamic)\n" + "[datetime(2015-12-31 23:59:59.9), false, guid(74be27de-1e4e-49d9-b579-fe0b331d3642), 12345, 1, 12345.6789, 'string value', 10s, decimal(0.10101), dynamic({\"a\":123, \"b\":\"hello\", \"c\":[1,2,3], \"d\":{}})];" + "range x from 1 to 100 step 1 | extend y=1 | join kind=fullouter dt on $left.y == $right.Long"; @BeforeEach public void setup() { LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder() .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.client = clientBuilder .buildClient(); } @Test public void testLogsQuery() { LogsQueryResult queryResults = client.queryWorkspace(WORKSPACE_ID, QUERY_STRING, new QueryTimeInterval(OffsetDateTime.of(LocalDateTime.of(2021, 01, 01, 0, 0), ZoneOffset.UTC), OffsetDateTime.of(LocalDateTime.of(2021, 06, 10, 0, 0), ZoneOffset.UTC))); assertEquals(1, queryResults.getAllTables().size()); assertEquals(1200, queryResults.getAllTables().get(0).getAllTableCells().size()); assertEquals(100, queryResults.getAllTables().get(0).getRows().size()); } @Test public void testLogsQueryBatch() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + "| take 3", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(1, responses.get(0).getAllTables().size()); assertEquals(24, responses.get(0).getAllTables().get(0).getAllTableCells().size()); assertEquals(2, responses.get(0).getAllTables().get(0).getRows().size()); assertEquals(1, responses.get(1).getAllTables().size()); assertEquals(36, responses.get(1).getAllTables().get(0).getAllTableCells().size()); assertEquals(3, responses.get(1).getAllTables().get(0).getRows().size()); } @Test @DisabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "LIVE", disabledReason = "multi-workspace " + "queries require sending logs to Azure Monitor first. So, run this test in playback or record mode only.") public void testMultipleWorkspaces() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, "union * | where TimeGenerated > ago(100d) | project TenantId | summarize count() by TenantId", null, new LogsQueryOptions() .setAdditionalWorkspaces(Arrays.asList("9dad0092-fd13-403a-b367-a189a090a541")), Context.NONE) .getValue(); assertEquals(1, queryResults.getAllTables().size()); assertEquals(2, queryResults .getAllTables() .get(0) .getRows() .stream() .map(row -> { System.out.println(row.getColumnValue("TenantId").get().getValueAsString()); return row.getColumnValue("TenantId").get(); }) .distinct() .count()); } @Test public void testBatchQueryPartialSuccess() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertEquals(LogsQueryResultStatus.FAILURE, responses.get(1).getQueryResultStatus()); assertNotNull(responses.get(1).getError()); assertEquals("BadArgumentError", responses.get(1).getError().getCode()); } @Test public void testStatistics() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true), Context.NONE).getValue(); assertEquals(1, queryResults.getAllTables().size()); assertNotNull(queryResults.getStatistics()); } @Test public void testBatchStatistics() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true)); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertNull(responses.get(0).getStatistics()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(1).getQueryResultStatus()); assertNull(responses.get(1).getError()); assertNotNull(responses.get(1).getStatistics()); } @Test public void testServerTimeout() { Random random = new Random(); while (true) { long count = 1000000000000L + random.nextInt(10000); try { client.queryWorkspaceWithResponse(WORKSPACE_ID, "range x from 1 to " + count + " step 1 | count", null, new LogsQueryOptions() .setServerTimeout(Duration.ofSeconds(5)), Context.NONE); } catch (Exception exception) { if (exception instanceof HttpResponseException) { HttpResponseException logsQueryException = (HttpResponseException) exception; if (logsQueryException.getResponse().getStatusCode() == 504) { break; } } } } } }
class LogsQueryClientTest extends TestBase { public static final String WORKSPACE_ID = Configuration.getGlobalConfiguration() .get("AZURE_MONITOR_LOGS_WORKSPACE_ID", "d2d0e126-fa1e-4b0a-b647-250cdd471e68"); private LogsQueryClient client; public static final String QUERY_STRING = "let dt = datatable (DateTime: datetime, Bool:bool, Guid: guid, Int: int, Long:long, Double: double, String: string, Timespan: timespan, Decimal: decimal, Dynamic: dynamic)\n" + "[datetime(2015-12-31 23:59:59.9), false, guid(74be27de-1e4e-49d9-b579-fe0b331d3642), 12345, 1, 12345.6789, 'string value', 10s, decimal(0.10101), dynamic({\"a\":123, \"b\":\"hello\", \"c\":[1,2,3], \"d\":{}})];" + "range x from 1 to 100 step 1 | extend y=1 | join kind=fullouter dt on $left.y == $right.Long"; @BeforeEach public void setup() { LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder() .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.client = clientBuilder .buildClient(); } @Test public void testLogsQuery() { LogsQueryResult queryResults = client.queryWorkspace(WORKSPACE_ID, QUERY_STRING, new QueryTimeInterval(OffsetDateTime.of(LocalDateTime.of(2021, 01, 01, 0, 0), ZoneOffset.UTC), OffsetDateTime.of(LocalDateTime.of(2021, 06, 10, 0, 0), ZoneOffset.UTC))); assertEquals(1, queryResults.getAllTables().size()); assertEquals(1200, queryResults.getAllTables().get(0).getAllTableCells().size()); assertEquals(100, queryResults.getAllTables().get(0).getRows().size()); } @Test public void testLogsQueryBatch() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + "| take 3", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(1, responses.get(0).getAllTables().size()); assertEquals(24, responses.get(0).getAllTables().get(0).getAllTableCells().size()); assertEquals(2, responses.get(0).getAllTables().get(0).getRows().size()); assertEquals(1, responses.get(1).getAllTables().size()); assertEquals(36, responses.get(1).getAllTables().get(0).getAllTableCells().size()); assertEquals(3, responses.get(1).getAllTables().get(0).getRows().size()); } @Test @DisabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "LIVE", disabledReason = "multi-workspace " + "queries require sending logs to Azure Monitor first. So, run this test in playback or record mode only.") public void testMultipleWorkspaces() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, "union * | where TimeGenerated > ago(100d) | project TenantId | summarize count() by TenantId", null, new LogsQueryOptions() .setAdditionalWorkspaces(Arrays.asList("9dad0092-fd13-403a-b367-a189a090a541")), Context.NONE) .getValue(); assertEquals(1, queryResults.getAllTables().size()); assertEquals(2, queryResults .getAllTables() .get(0) .getRows() .stream() .map(row -> { System.out.println(row.getColumnValue("TenantId").get().getValueAsString()); return row.getColumnValue("TenantId").get(); }) .distinct() .count()); } @Test public void testBatchQueryPartialSuccess() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take 2", null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING + " | take", null); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertEquals(LogsQueryResultStatus.FAILURE, responses.get(1).getQueryResultStatus()); assertNotNull(responses.get(1).getError()); assertEquals("BadArgumentError", responses.get(1).getError().getCode()); } @Test public void testStatistics() { LogsQueryResult queryResults = client.queryWorkspaceWithResponse(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true), Context.NONE).getValue(); assertEquals(1, queryResults.getAllTables().size()); assertNotNull(queryResults.getStatistics()); } @Test public void testBatchStatistics() { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null); logsBatchQuery.addWorkspaceQuery(WORKSPACE_ID, QUERY_STRING, null, new LogsQueryOptions().setIncludeStatistics(true)); LogsBatchQueryResultCollection batchResultCollection = client .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue(); List<LogsBatchQueryResult> responses = batchResultCollection.getBatchResults(); assertEquals(2, responses.size()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(0).getQueryResultStatus()); assertNull(responses.get(0).getError()); assertNull(responses.get(0).getStatistics()); assertEquals(LogsQueryResultStatus.SUCCESS, responses.get(1).getQueryResultStatus()); assertNull(responses.get(1).getError()); assertNotNull(responses.get(1).getStatistics()); } @Test public void testServerTimeout() { Random random = new Random(); while (true) { long count = 1000000000000L + random.nextInt(10000); try { client.queryWorkspaceWithResponse(WORKSPACE_ID, "range x from 1 to " + count + " step 1 | count", null, new LogsQueryOptions() .setServerTimeout(Duration.ofSeconds(5)), Context.NONE); } catch (Exception exception) { if (exception instanceof HttpResponseException) { HttpResponseException logsQueryException = (HttpResponseException) exception; if (logsQueryException.getResponse().getStatusCode() == 504) { break; } } } } } }
looks like can build this once before injection above
private Context startSpan(HttpPipelineCallContext azContext) { Context parentContext = getTraceContextOrCurrent(azContext); HttpRequest request = azContext.getHttpRequest(); String methodName = request.getHttpMethod().toString(); Span span = tracer.spanBuilder("HTTP " + methodName) .setAttribute(HTTP_METHOD, methodName) .setAttribute(HTTP_URL, request.getUrl().toString()) .setParent(parentContext) .setSpanKind(SpanKind.CLIENT) .startSpan(); if (span.isRecording()) { addPostSamplingAttributes(span, request, azContext); } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { traceContextFormat.inject(parentContext.with(span), request, contextSetter); } return parentContext.with(span); }
return parentContext.with(span);
private Context startSpan(HttpPipelineCallContext azContext) { Context parentContext = getTraceContextOrCurrent(azContext); HttpRequest request = azContext.getHttpRequest(); String methodName = request.getHttpMethod().toString(); Span span = tracer.spanBuilder("HTTP " + methodName) .setAttribute(HTTP_METHOD, methodName) .setAttribute(HTTP_URL, request.getUrl().toString()) .setParent(parentContext) .setSpanKind(SpanKind.CLIENT) .startSpan(); if (span.isRecording()) { addPostSamplingAttributes(span, request, azContext); } Context traceContext = parentContext.with(span); traceContextFormat.inject(traceContext, request, contextSetter); return traceContext; }
class implements W3C distributed tracing protocol and injects SpanContext into the outgoing http private final TextMapPropagator traceContextFormat = W3CTraceContextPropagator.getInstance(); @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ((boolean) context.getData(DISABLE_TRACING_KEY).orElse(false)) { return next.process(); } return ScalarPropagatingMono.INSTANCE .flatMap(ignored -> next.process()) .doOnEach(OpenTelemetryHttpPolicy::handleResponse) .contextWrite(reactor.util.context.Context.of(REACTOR_PARENT_TRACE_CONTEXT_KEY, startSpan(context))); }
class implements W3C distributed tracing protocol and injects SpanContext into the outgoing http private final TextMapPropagator traceContextFormat = W3CTraceContextPropagator.getInstance(); @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ((boolean) context.getData(DISABLE_TRACING_KEY).orElse(false)) { return next.process(); } return ScalarPropagatingMono.INSTANCE .flatMap(ignored -> next.process()) .doOnEach(OpenTelemetryHttpPolicy::handleResponse) .contextWrite(reactor.util.context.Context.of(REACTOR_PARENT_TRACE_CONTEXT_KEY, startSpan(context))); }
the injectors check this, so no need here
private Context startSpan(HttpPipelineCallContext azContext) { Context parentContext = getTraceContextOrCurrent(azContext); HttpRequest request = azContext.getHttpRequest(); String methodName = request.getHttpMethod().toString(); Span span = tracer.spanBuilder("HTTP " + methodName) .setAttribute(HTTP_METHOD, methodName) .setAttribute(HTTP_URL, request.getUrl().toString()) .setParent(parentContext) .setSpanKind(SpanKind.CLIENT) .startSpan(); if (span.isRecording()) { addPostSamplingAttributes(span, request, azContext); } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { traceContextFormat.inject(parentContext.with(span), request, contextSetter); } return parentContext.with(span); }
if (spanContext.isValid()) {
private Context startSpan(HttpPipelineCallContext azContext) { Context parentContext = getTraceContextOrCurrent(azContext); HttpRequest request = azContext.getHttpRequest(); String methodName = request.getHttpMethod().toString(); Span span = tracer.spanBuilder("HTTP " + methodName) .setAttribute(HTTP_METHOD, methodName) .setAttribute(HTTP_URL, request.getUrl().toString()) .setParent(parentContext) .setSpanKind(SpanKind.CLIENT) .startSpan(); if (span.isRecording()) { addPostSamplingAttributes(span, request, azContext); } Context traceContext = parentContext.with(span); traceContextFormat.inject(traceContext, request, contextSetter); return traceContext; }
class implements W3C distributed tracing protocol and injects SpanContext into the outgoing http private final TextMapPropagator traceContextFormat = W3CTraceContextPropagator.getInstance(); @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ((boolean) context.getData(DISABLE_TRACING_KEY).orElse(false)) { return next.process(); } return ScalarPropagatingMono.INSTANCE .flatMap(ignored -> next.process()) .doOnEach(OpenTelemetryHttpPolicy::handleResponse) .contextWrite(reactor.util.context.Context.of(REACTOR_PARENT_TRACE_CONTEXT_KEY, startSpan(context))); }
class implements W3C distributed tracing protocol and injects SpanContext into the outgoing http private final TextMapPropagator traceContextFormat = W3CTraceContextPropagator.getInstance(); @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ((boolean) context.getData(DISABLE_TRACING_KEY).orElse(false)) { return next.process(); } return ScalarPropagatingMono.INSTANCE .flatMap(ignored -> next.process()) .doOnEach(OpenTelemetryHttpPolicy::handleResponse) .contextWrite(reactor.util.context.Context.of(REACTOR_PARENT_TRACE_CONTEXT_KEY, startSpan(context))); }
maybe try-with-resource instead?
public void subscribe(CoreSubscriber<? super Object> actual) { Context traceContext = actual.currentContext().getOrDefault(REACTOR_PARENT_TRACE_CONTEXT_KEY, null); if (traceContext != null) { Object agentContext = OpenTelemetrySpanSuppressionHelper.registerClientSpan(traceContext); AutoCloseable closeable = OpenTelemetrySpanSuppressionHelper.makeCurrent(agentContext, traceContext); actual.onSubscribe(Operators.scalarSubscription(actual, value)); try { closeable.close(); } catch (Throwable ignored) { } } else { actual.onSubscribe(Operators.scalarSubscription(actual, value)); } }
try {
public void subscribe(CoreSubscriber<? super Object> actual) { Context traceContext = actual.currentContext().getOrDefault(REACTOR_PARENT_TRACE_CONTEXT_KEY, null); if (traceContext != null) { Object agentContext = OpenTelemetrySpanSuppressionHelper.registerClientSpan(traceContext); AutoCloseable closeable = OpenTelemetrySpanSuppressionHelper.makeCurrent(agentContext, traceContext); actual.onSubscribe(Operators.scalarSubscription(actual, value)); try { closeable.close(); } catch (Throwable ignored) { } } else { actual.onSubscribe(Operators.scalarSubscription(actual, value)); } }
class ScalarPropagatingMono extends Mono<Object> { public static final Mono<Object> INSTANCE = new ScalarPropagatingMono(); private final Object value = new Object(); private ScalarPropagatingMono() { } @Override }
class ScalarPropagatingMono extends Mono<Object> { public static final Mono<Object> INSTANCE = new ScalarPropagatingMono(); private final Object value = new Object(); private ScalarPropagatingMono() { } @Override }
I think `span` is never null (similar for other span null checks below)
public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); Span span = getSpanOrCurrent(context); if (span == null) { return; } if (span.isRecording()) { span = HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); }
if (span == null) {
public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrCurrent(context); if (span != null && span.isRecording()) { span.setAttribute(key, value); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrCurrent(context); if (span == null) { logger.verbose("Failed to find span to end it."); return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { logger.verbose("Failed to find spanBuilder to link it."); return; } final SpanContext spanContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); if (spanContext == null) { logger.verbose("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrCurrent(context); if (currentSpan == null) { logger.verbose("Failed to find a starting span to associate the {} with.", eventName); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrDefault(context, AZ_TRACING_NAMESPACE_KEY, null, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrDefault(context, USER_SPAN_NAME_KEY, null, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrDefault(context, SCOPE_KEY, null, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { SpanContext spanContext = getSpanOrCurrent(context).getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrDefault(context, ENTITY_PATH_KEY, null, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrDefault(context, HOST_NAME_KEY, null, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrDefault(context, MESSAGE_ENQUEUED_TIME, null, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param defaultValue the value to return in data not found. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrDefault(Context context, String key, T defaultValue, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return defaultValue; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context otelContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? otelContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or {@link Span */ @SuppressWarnings("deprecation") private Span getSpanOrCurrent(Context azContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? Span.current() : Span.fromContext(traceContext); } }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span.setAttribute(key, value); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return; } final SpanContext spanContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); if (spanContext == null) { return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { logger.verbose("There is no OpenTelemetry Context on the context, cannot make it current"); return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrNull(context); if (currentSpan == null) { logger.verbose("There is no OpenTelemetry Span or Context on the context, cannot add event"); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrNull(context, AZ_TRACING_NAMESPACE_KEY, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrNull(context, USER_SPAN_NAME_KEY, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrNull(context, SCOPE_KEY, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { Span span = getSpanOrNull(context); if (span == null) { return context; } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrNull(context, ENTITY_PATH_KEY, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrNull(context, HOST_NAME_KEY, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrNull(context, MESSAGE_ENQUEUED_TIME, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrNull(Context context, String key, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return null; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context defaultContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? defaultContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) */ @SuppressWarnings("deprecation") private Span getSpanOrNull(Context azContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? null : Span.fromContext(traceContext); } }
`userParentSpan` should be a context object instead?
public void addDataToContext() { final String hostNameValue = "host-name-value"; final String entityPathValue = "entity-path-value"; final String userParentSpan = "user-parent-span"; Context parentSpanContext = new Context(PARENT_TRACE_CONTEXT_KEY, userParentSpan); Context updatedContext = parentSpanContext.addData(HOST_NAME_KEY, hostNameValue) .addData(ENTITY_PATH_KEY, entityPathValue); System.out.printf("Hostname value: %s%n", updatedContext.getData(HOST_NAME_KEY).get()); System.out.printf("Entity Path value: %s%n", updatedContext.getData(ENTITY_PATH_KEY).get()); }
Context parentSpanContext = new Context(PARENT_TRACE_CONTEXT_KEY, userParentSpan);
public void addDataToContext() { final String hostNameValue = "host-name-value"; final String entityPathValue = "entity-path-value"; final TraceContext parentContext = TraceContext.root(); Context parentSpanContext = new Context(PARENT_TRACE_CONTEXT_KEY, parentContext); Context updatedContext = parentSpanContext.addData(HOST_NAME_KEY, hostNameValue) .addData(ENTITY_PATH_KEY, entityPathValue); System.out.printf("Hostname value: %s%n", updatedContext.getData(HOST_NAME_KEY).get()); System.out.printf("Entity Path value: %s%n", updatedContext.getData(ENTITY_PATH_KEY).get()); }
class ContextJavaDocCodeSnippets { /** * Code snippet for {@link Context */ public void constructContextObject() { Context emptyContext = Context.NONE; Context keyValueContext = new Context(USER_SPAN_NAME_KEY, "span-name"); } /** * Code snippet for creating Context object using key-value pair map */ public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get()); } /** * Code snippet for {@link Context */ /** * Code snippet for {@link Context */ public void getDataContext() { final String key1 = "Key1"; final String value1 = "first-value"; Context context = new Context(key1, value1); Optional<Object> optionalObject = context.getData(key1); if (optionalObject.isPresent()) { System.out.printf("Key1 value: %s%n", optionalObject.get()); } else { System.out.println("Key1 does not exist or have data."); } } /** * Code snippet for {@link Context */ public void getValues() { final String key1 = "Key1"; final String value1 = "first-value"; final String key2 = "Key2"; final String value2 = "second-value"; Context context = new Context(key1, value1) .addData(key2, value2); Map<Object, Object> contextValues = context.getValues(); if (contextValues.containsKey(key1)) { System.out.printf("Key1 value: %s%n", contextValues.get(key1)); } else { System.out.println("Key1 does not exist."); } if (contextValues.containsKey(key2)) { System.out.printf("Key2 value: %s%n", contextValues.get(key2)); } else { System.out.println("Key2 does not exist."); } } }
class ContextJavaDocCodeSnippets { /** * Code snippet for {@link Context */ public void constructContextObject() { Context emptyContext = Context.NONE; Context keyValueContext = new Context(USER_SPAN_NAME_KEY, "span-name"); } /** * Code snippet for creating Context object using key-value pair map */ public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get()); } /** * Code snippet for {@link Context */ /** * Code snippet for {@link Context */ public void getDataContext() { final String key1 = "Key1"; final String value1 = "first-value"; Context context = new Context(key1, value1); Optional<Object> optionalObject = context.getData(key1); if (optionalObject.isPresent()) { System.out.printf("Key1 value: %s%n", optionalObject.get()); } else { System.out.println("Key1 does not exist or have data."); } } /** * Code snippet for {@link Context */ public void getValues() { final String key1 = "Key1"; final String value1 = "first-value"; final String key2 = "Key2"; final String value2 = "second-value"; Context context = new Context(key1, value1) .addData(key2, value2); Map<Object, Object> contextValues = context.getValues(); if (contextValues.containsKey(key1)) { System.out.printf("Key1 value: %s%n", contextValues.get(key1)); } else { System.out.println("Key1 does not exist."); } if (contextValues.containsKey(key2)) { System.out.printf("Key2 value: %s%n", contextValues.get(key2)); } else { System.out.println("Key2 does not exist."); } } static class TraceContext { public static TraceContext root() { return new TraceContext(); } } }
yeah, I've been there, but then stylecheck complains about the unused scope and AutoCloseable (I need it to hide shaded Scope) close needs try/catch. So this version looks cleaner.
public void subscribe(CoreSubscriber<? super Object> actual) { Context traceContext = actual.currentContext().getOrDefault(REACTOR_PARENT_TRACE_CONTEXT_KEY, null); if (traceContext != null) { Object agentContext = OpenTelemetrySpanSuppressionHelper.registerClientSpan(traceContext); AutoCloseable closeable = OpenTelemetrySpanSuppressionHelper.makeCurrent(agentContext, traceContext); actual.onSubscribe(Operators.scalarSubscription(actual, value)); try { closeable.close(); } catch (Throwable ignored) { } } else { actual.onSubscribe(Operators.scalarSubscription(actual, value)); } }
try {
public void subscribe(CoreSubscriber<? super Object> actual) { Context traceContext = actual.currentContext().getOrDefault(REACTOR_PARENT_TRACE_CONTEXT_KEY, null); if (traceContext != null) { Object agentContext = OpenTelemetrySpanSuppressionHelper.registerClientSpan(traceContext); AutoCloseable closeable = OpenTelemetrySpanSuppressionHelper.makeCurrent(agentContext, traceContext); actual.onSubscribe(Operators.scalarSubscription(actual, value)); try { closeable.close(); } catch (Throwable ignored) { } } else { actual.onSubscribe(Operators.scalarSubscription(actual, value)); } }
class ScalarPropagatingMono extends Mono<Object> { public static final Mono<Object> INSTANCE = new ScalarPropagatingMono(); private final Object value = new Object(); private ScalarPropagatingMono() { } @Override }
class ScalarPropagatingMono extends Mono<Object> { public static final Mono<Object> INSTANCE = new ScalarPropagatingMono(); private final Object value = new Object(); private ScalarPropagatingMono() { } @Override }
great catch! I realized that `getSpanOrCurrent()` is not so good - we should not use it in `endSpan` and need to be more explicit. I changed it to getSpanOrDefault and sometimes pass null as default.
public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); Span span = getSpanOrCurrent(context); if (span == null) { return; } if (span.isRecording()) { span = HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); }
if (span == null) {
public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrCurrent(context); if (span != null && span.isRecording()) { span.setAttribute(key, value); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrCurrent(context); if (span == null) { logger.verbose("Failed to find span to end it."); return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { logger.verbose("Failed to find spanBuilder to link it."); return; } final SpanContext spanContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); if (spanContext == null) { logger.verbose("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrCurrent(context); if (currentSpan == null) { logger.verbose("Failed to find a starting span to associate the {} with.", eventName); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrDefault(context, AZ_TRACING_NAMESPACE_KEY, null, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrDefault(context, USER_SPAN_NAME_KEY, null, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrDefault(context, SCOPE_KEY, null, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { SpanContext spanContext = getSpanOrCurrent(context).getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrDefault(context, ENTITY_PATH_KEY, null, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrDefault(context, HOST_NAME_KEY, null, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrDefault(context, MESSAGE_ENQUEUED_TIME, null, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param defaultValue the value to return in data not found. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrDefault(Context context, String key, T defaultValue, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return defaultValue; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context otelContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? otelContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or {@link Span */ @SuppressWarnings("deprecation") private Span getSpanOrCurrent(Context azContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? Span.current() : Span.fromContext(traceContext); } }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span.setAttribute(key, value); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return; } final SpanContext spanContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); if (spanContext == null) { return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { logger.verbose("There is no OpenTelemetry Context on the context, cannot make it current"); return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrNull(context); if (currentSpan == null) { logger.verbose("There is no OpenTelemetry Span or Context on the context, cannot add event"); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrNull(context, AZ_TRACING_NAMESPACE_KEY, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrNull(context, USER_SPAN_NAME_KEY, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrNull(context, SCOPE_KEY, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { Span span = getSpanOrNull(context); if (span == null) { return context; } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrNull(context, ENTITY_PATH_KEY, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrNull(context, HOST_NAME_KEY, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrNull(context, MESSAGE_ENQUEUED_TIME, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrNull(Context context, String key, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return null; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context defaultContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? defaultContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) */ @SuppressWarnings("deprecation") private Span getSpanOrNull(Context azContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? null : Span.fromContext(traceContext); } }
oh yes, this makes sense not to use Context.current() in `end` 👍
public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); Span span = getSpanOrCurrent(context); if (span == null) { return; } if (span.isRecording()) { span = HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); }
if (span == null) {
public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrCurrent(context); if (span != null && span.isRecording()) { span.setAttribute(key, value); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrCurrent(context); if (span == null) { logger.verbose("Failed to find span to end it."); return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { logger.verbose("Failed to find spanBuilder to link it."); return; } final SpanContext spanContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); if (spanContext == null) { logger.verbose("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrCurrent(context); if (currentSpan == null) { logger.verbose("Failed to find a starting span to associate the {} with.", eventName); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrDefault(context, AZ_TRACING_NAMESPACE_KEY, null, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrDefault(context, USER_SPAN_NAME_KEY, null, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrDefault(context, SCOPE_KEY, null, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { SpanContext spanContext = getSpanOrCurrent(context).getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrDefault(context, ENTITY_PATH_KEY, null, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrDefault(context, HOST_NAME_KEY, null, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrDefault(context, MESSAGE_ENQUEUED_TIME, null, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param defaultValue the value to return in data not found. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrDefault(Context context, String key, T defaultValue, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return defaultValue; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context otelContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? otelContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or {@link Span */ @SuppressWarnings("deprecation") private Span getSpanOrCurrent(Context azContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? Span.current() : Span.fromContext(traceContext); } }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span.setAttribute(key, value); } } /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return; } final SpanContext spanContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); if (spanContext == null) { return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { logger.verbose("There is no OpenTelemetry Context on the context, cannot make it current"); return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrNull(context); if (currentSpan == null) { logger.verbose("There is no OpenTelemetry Span or Context on the context, cannot add event"); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrNull(context, AZ_TRACING_NAMESPACE_KEY, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrNull(context, USER_SPAN_NAME_KEY, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrNull(context, SCOPE_KEY, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { Span span = getSpanOrNull(context); if (span == null) { return context; } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrNull(context, ENTITY_PATH_KEY, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrNull(context, HOST_NAME_KEY, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrNull(context, MESSAGE_ENQUEUED_TIME, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrNull(Context context, String key, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return null; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context defaultContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? defaultContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) */ @SuppressWarnings("deprecation") private Span getSpanOrNull(Context azContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? null : Span.fromContext(traceContext); } }
what do you think of defaulting to `null` here too, and only using `current()` as fallback during `start`?
public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrDefault(context, Span.current()); if (span.isRecording()) { span.setAttribute(key, value); } }
final Span span = getSpanOrDefault(context, Span.current());
public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { logger.verbose("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span.setAttribute(key, value); } }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); Span span = getSpanOrDefault(context, null); if (span == null) { return; } if (span.isRecording()) { span = HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrDefault(context, null); if (span == null) { logger.verbose("Failed to find span to end it."); return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrDefault(context, SPAN_BUILDER_KEY, null, SpanBuilder.class); if (spanBuilder == null) { logger.verbose("Failed to find spanBuilder to link it."); return; } final SpanContext spanContext = getOrDefault(context, SPAN_CONTEXT_KEY, null, SpanContext.class); if (spanContext == null) { logger.verbose("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrDefault(context, Span.current()); if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrDefault(context, AZ_TRACING_NAMESPACE_KEY, null, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrDefault(context, USER_SPAN_NAME_KEY, null, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrDefault(context, SCOPE_KEY, null, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { Span span = getSpanOrDefault(context, null); if (span == null) { return context; } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrDefault(context, ENTITY_PATH_KEY, null, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrDefault(context, HOST_NAME_KEY, null, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrDefault(context, MESSAGE_ENQUEUED_TIME, null, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param defaultValue the value to return in data not found. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrDefault(Context context, String key, T defaultValue, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return defaultValue; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context defaultContext) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? defaultContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or {@link Span */ @SuppressWarnings("deprecation") private Span getSpanOrDefault(Context azContext, Span defaultSpan) { io.opentelemetry.context.Context traceContext = getOrDefault(azContext, PARENT_TRACE_CONTEXT_KEY, null, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrDefault(azContext, PARENT_SPAN_KEY, null, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? defaultSpan : Span.fromContext(traceContext); } }
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private final Tracer tracer; /** * Creates new {@link OpenTelemetryTracer} using default global tracer - * {@link GlobalOpenTelemetry * */ public OpenTelemetryTracer() { this(GlobalOpenTelemetry.getTracer("Azure-OpenTelemetry")); } /** * Creates new {@link OpenTelemetryTracer} that wraps {@link io.opentelemetry.api.trace.Tracer}. * Use it for tests. * * @param tracer {@link io.opentelemetry.api.trace.Tracer} instance. */ OpenTelemetryTracer(Tracer tracer) { this.tracer = tracer; } static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, SpanKind.INTERNAL, null, context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, StartSpanOptions options, Context context) { Objects.requireNonNull(options, "'options' cannot be null."); SpanBuilder spanBuilder = createSpanBuilder(spanName, null, convertToOtelKind(options.getSpanKind()), options.getAttributes(), context); return startSpanInternal(spanBuilder, null, context); } /** * {@inheritDoc} */ @Override public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); SpanBuilder spanBuilder; switch (processKind) { case SEND: spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return context; } return startSpanInternal(spanBuilder, this::addMessagingAttributes, context); case MESSAGE: spanBuilder = createSpanBuilder(spanName, null, SpanKind.PRODUCER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return setDiagnosticId(context); case PROCESS: SpanContext remoteParentContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); spanBuilder = createSpanBuilder(spanName, remoteParentContext, SpanKind.CONSUMER, null, context); context = startSpanInternal(spanBuilder, this::addMessagingAttributes, context); return context.addData(SCOPE_KEY, makeSpanCurrent(context)); default: return context; } } /** * {@inheritDoc} */ @Override public void end(int responseCode, Throwable throwable, Context context) { Objects.requireNonNull(context, "'context' cannot be null."); final Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { HttpTraceUtil.setSpanStatus(span, responseCode, throwable); } span.end(); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Context setSpanName(String spanName, Context context) { return context.addData(USER_SPAN_NAME_KEY, spanName); } /** * {@inheritDoc} */ @Override public void end(String statusMessage, Throwable throwable, Context context) { Span span = getSpanOrNull(context); if (span == null) { return; } if (span.isRecording()) { span = AmqpTraceUtil.parseStatusMessage(span, statusMessage, throwable); } span.end(); endScope(context); } @Override public void addLink(Context context) { final SpanBuilder spanBuilder = getOrNull(context, SPAN_BUILDER_KEY, SpanBuilder.class); if (spanBuilder == null) { return; } final SpanContext spanContext = getOrNull(context, SPAN_CONTEXT_KEY, SpanContext.class); if (spanContext == null) { return; } spanBuilder.addLink(spanContext); } /** * {@inheritDoc} */ @Override public Context extractContext(String diagnosticId, Context context) { return AmqpPropagationFormatUtil.extractContext(diagnosticId, context); } /** * {@inheritDoc} */ @Override public Context getSharedSpanBuilder(String spanName, Context context) { return context.addData(SPAN_BUILDER_KEY, createSpanBuilder(spanName, null, SpanKind.CLIENT, null, context)); } /** * {@inheritDoc} */ @Override public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { logger.verbose("There is no OpenTelemetry Context on the context, cannot make it current"); return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("deprecation") public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp) { addEvent(eventName, traceEventAttributes, timestamp, new Context(PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.current())); } /** * {@inheritDoc} */ @Override public void addEvent(String eventName, Map<String, Object> traceEventAttributes, OffsetDateTime timestamp, Context context) { Objects.requireNonNull(eventName, "'eventName' cannot be null."); Span currentSpan = getSpanOrNull(context); if (currentSpan == null) { logger.verbose("There is no OpenTelemetry Span or Context on the context, cannot add event"); return; } if (timestamp == null) { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes)); } else { currentSpan.addEvent( eventName, traceEventAttributes == null ? Attributes.empty() : convertToOtelAttributes(traceEventAttributes), timestamp.toInstant() ); } } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanBuilder SpanBuilder for the span. Must be created before calling this method * @param setAttributes Callback to populate attributes for the span. * @return A {@link Context} with created {@link Span}. */ private Context startSpanInternal(SpanBuilder spanBuilder, java.util.function.BiConsumer<Span, Context> setAttributes, Context context) { Objects.requireNonNull(spanBuilder, "'spanBuilder' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrNull(context, AZ_TRACING_NAMESPACE_KEY, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, tracingNamespace); } if (setAttributes != null) { setAttributes.accept(span, context); } } return context.addData(PARENT_TRACE_CONTEXT_KEY, getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()).with(span)); } /** * Returns a {@link SpanBuilder} to create and start a new child {@link Span} with parent being the designated * {@link Span}. * * @param spanName The name of the returned Span. * @param remoteParentContext Remote parent context if any, or {@code null} otherwise. * @param spanKind Kind of the span to create. * @param beforeSaplingAttributes Optional attributes available when span starts and important for sampling. * @param context The context containing the span and the span name. * @return A {@link SpanBuilder} to create and start a new {@link Span}. */ @SuppressWarnings("unchecked") private SpanBuilder createSpanBuilder(String spanName, SpanContext remoteParentContext, SpanKind spanKind, Map<String, Object> beforeSaplingAttributes, Context context) { String spanNameKey = getOrNull(context, USER_SPAN_NAME_KEY, String.class); if (spanNameKey == null) { spanNameKey = spanName; } SpanBuilder spanBuilder = tracer.spanBuilder(spanNameKey) .setSpanKind(spanKind); io.opentelemetry.context.Context parentContext = getTraceContextOrDefault(context, io.opentelemetry.context.Context.current()); if (remoteParentContext != null) { spanBuilder.setParent(parentContext.with(Span.wrap(remoteParentContext))); } else { spanBuilder.setParent(parentContext); } if (!CoreUtils.isNullOrEmpty(beforeSaplingAttributes)) { Attributes otelAttributes = convertToOtelAttributes(beforeSaplingAttributes); otelAttributes.forEach( (key, value) -> spanBuilder.setAttribute((AttributeKey<Object>) key, value)); } return spanBuilder; } /** * Ends current scope on the context. * * @param context Context instance with the scope to end. */ private void endScope(Context context) { Scope scope = getOrNull(context, SCOPE_KEY, Scope.class); if (scope != null) { scope.close(); } } /* * Converts our SpanKind to OpenTelemetry SpanKind. */ private SpanKind convertToOtelKind(com.azure.core.util.tracing.SpanKind kind) { switch (kind) { case CLIENT: return SpanKind.CLIENT; case SERVER: return SpanKind.SERVER; case CONSUMER: return SpanKind.CONSUMER; case PRODUCER: return SpanKind.PRODUCER; default: return SpanKind.INTERNAL; } } /** * Maps span/event properties to OpenTelemetry attributes. * * @param attributes the attributes provided by the client SDK's. * @return the OpenTelemetry typed {@link Attributes}. */ private Attributes convertToOtelAttributes(Map<String, Object> attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); attributes.forEach((key, value) -> { if (value instanceof Boolean) { attributesBuilder.put(key, (boolean) value); } else if (value instanceof String) { attributesBuilder.put(key, String.valueOf(value)); } else if (value instanceof Double) { attributesBuilder.put(key, (Double) value); } else if (value instanceof Long) { attributesBuilder.put(key, (Long) value); } else if (value instanceof String[]) { attributesBuilder.put(key, (String[]) value); } else if (value instanceof long[]) { attributesBuilder.put(key, (long[]) value); } else if (value instanceof double[]) { attributesBuilder.put(key, (double[]) value); } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { logger.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); } /** * Extracts the {@link SpanContext trace identifiers} and the {@link SpanContext} of the current tracing span as * text and returns in a {@link Context} object. * * @param context The context with current tracing span describing unique message context. * @return The {@link Context} containing the {@link SpanContext} and trace-parent of the current span. */ private Context setDiagnosticId(Context context) { Span span = getSpanOrNull(context); if (span == null) { return context; } SpanContext spanContext = span.getSpanContext(); if (spanContext.isValid()) { final String traceparent = AmqpPropagationFormatUtil.getDiagnosticId(spanContext); if (traceparent == null) { return context; } return context.addData(DIAGNOSTIC_ID_KEY, traceparent).addData(SPAN_CONTEXT_KEY, spanContext); } return context; } /** * Extracts request attributes from the given {@link Context} and adds it to the started span. * * @param span The span to which request attributes are to be added. * @param context The context containing the request attributes. */ private void addMessagingAttributes(Span span, Context context) { Objects.requireNonNull(span, "'span' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); String entityPath = getOrNull(context, ENTITY_PATH_KEY, String.class); if (entityPath != null) { span.setAttribute(MESSAGE_BUS_DESTINATION, entityPath); } String hostName = getOrNull(context, HOST_NAME_KEY, String.class); if (hostName != null) { span.setAttribute(PEER_ENDPOINT, hostName); } Long messageEnqueuedTime = getOrNull(context, MESSAGE_ENQUEUED_TIME, Long.class); if (messageEnqueuedTime != null) { span.setAttribute(MESSAGE_ENQUEUED_TIME, messageEnqueuedTime); } } /** * Returns the value of the specified key from the context. * * @param key The name of the attribute that needs to be extracted from the {@link Context}. * @param clazz clazz the type of raw class to find data for. * @param context The context containing the specified key. * @return The T type of raw class object */ @SuppressWarnings("unchecked") private <T> T getOrNull(Context context, String key, Class<T> clazz) { final Optional<Object> optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return null; }); return (T) result; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) or default value. */ @SuppressWarnings("deprecation") private io.opentelemetry.context.Context getTraceContextOrDefault(Context azContext, io.opentelemetry.context.Context defaultContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { traceContext = io.opentelemetry.context.Context.current().with(parentSpan); } } return traceContext == null ? defaultContext : traceContext; } /** * Returns OpenTelemetry trace context from given com.azure.core.Context under PARENT_TRACE_CONTEXT_KEY * or PARENT_SPAN_KEY (for backward-compatibility) */ @SuppressWarnings("deprecation") private Span getSpanOrNull(Context azContext) { io.opentelemetry.context.Context traceContext = getOrNull(azContext, PARENT_TRACE_CONTEXT_KEY, io.opentelemetry.context.Context.class); if (traceContext == null) { Span parentSpan = getOrNull(azContext, PARENT_SPAN_KEY, Span.class); if (parentSpan != null) { return parentSpan; } } return traceContext == null ? null : Span.fromContext(traceContext); } }
We should also log this exception. For our own debugging purposes. Swallowing is not a good practice, even if it is not actionable.
private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { return version; } }
private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); public static final Base64.Decoder Base64UrlDecoder = Base64.getUrlDecoder(); private static final ObjectMapper simpleObjectMapper = new ObjectMapper(); private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); static { Utils.simpleObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); Utils.simpleObjectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); int javaVersion = getJavaVersion(); if (javaVersion != -1 && javaVersion < 16) { Utils.simpleObjectMapper.registerModule(new AfterburnerModule()); } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUtf16Bytes(String str) { return str.getBytes(StandardCharsets.UTF_16LE); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } /** * Checks whether the specified link is Name based or not * * @param link the link to analyze. * @return true or false */ public static boolean isNameBased(String link) { if (StringUtils.isEmpty(link)) { return false; } if (link.startsWith("/") && link.length() > 1) { link = link.substring(1); } String[] parts = StringUtils.split(link, "/"); if (parts.length == 0 || StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (parts.length < 2 || StringUtils.isEmpty(parts[1])) { return false; } String databaseID = parts[1]; if (databaseID.length() != 8) { return true; } byte[] buffer = ResourceId.fromBase64String(databaseID); if (buffer.length != 4) { return true; } return false; } /** * Checks whether the specified link is a Database Self Link or a Database * ID based link * * @param link the link to analyze. * @return true or false */ public static boolean isDatabaseLink(String link) { if (StringUtils.isEmpty(link)) { return false; } link = trimBeginningAndEndingSlashes(link); String[] parts = StringUtils.split(link, "/"); if (parts.length != 2) { return false; } if (StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (StringUtils.isEmpty(parts[1])) { return false; } return true; } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static Map<String, String> paramEncode(Map<String, String> queryParams) { HashMap<String, String> map = new HashMap<>(); for(Map.Entry<String, String> paramEntry: queryParams.entrySet()) { try { map.put(paramEntry.getKey(), URLEncoder.encode(paramEntry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } return map; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static Boolean isCollectionPartitioned(DocumentCollection collection) { if (collection == null) { throw new IllegalArgumentException("collection"); } return collection.getPartitionKey() != null && collection.getPartitionKey().getPaths() != null && collection.getPartitionKey().getPaths().size() > 0; } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } public static boolean isFeedRequest(OperationType requestOperationType) { return requestOperationType == OperationType.Create || requestOperationType == OperationType.Upsert || requestOperationType == OperationType.ReadFeed || requestOperationType == OperationType.Query || requestOperationType == OperationType.SqlQuery || requestOperationType == OperationType.HeadFeed; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.SDK_VERSION); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = osName.replaceAll("\\s", ""); String userAgent = String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); return userAgent; } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String zonedDateTimeAsUTCRFC1123(OffsetDateTime offsetDateTime){ return Utils.RFC_1123_DATE_TIME.format(offsetDateTime.atZoneSameInstant(GMT_ZONE_ID)); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val.intValue() : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <V> List<V> immutableListOf(V v1) { List<V> list = new ArrayList<>(); list.add(v1); return Collections.unmodifiableList(list); } public static <K, V> Map<K, V>immutableMapOf() { return Collections.emptyMap(); } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<K ,V>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<T>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static ByteBuffer toByteBuffer(byte[] bytes) { return ByteBuffer.wrap(bytes); } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static byte[] serializeObjectToByteArray(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); public static final Base64.Decoder Base64UrlDecoder = Base64.getUrlDecoder(); private static final ObjectMapper simpleObjectMapper = new ObjectMapper(); private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); static { Utils.simpleObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); Utils.simpleObjectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); int javaVersion = getJavaVersion(); if (javaVersion != -1 && javaVersion < 16) { Utils.simpleObjectMapper.registerModule(new AfterburnerModule()); } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUtf16Bytes(String str) { return str.getBytes(StandardCharsets.UTF_16LE); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } /** * Checks whether the specified link is Name based or not * * @param link the link to analyze. * @return true or false */ public static boolean isNameBased(String link) { if (StringUtils.isEmpty(link)) { return false; } if (link.startsWith("/") && link.length() > 1) { link = link.substring(1); } String[] parts = StringUtils.split(link, "/"); if (parts.length == 0 || StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (parts.length < 2 || StringUtils.isEmpty(parts[1])) { return false; } String databaseID = parts[1]; if (databaseID.length() != 8) { return true; } byte[] buffer = ResourceId.fromBase64String(databaseID); if (buffer.length != 4) { return true; } return false; } /** * Checks whether the specified link is a Database Self Link or a Database * ID based link * * @param link the link to analyze. * @return true or false */ public static boolean isDatabaseLink(String link) { if (StringUtils.isEmpty(link)) { return false; } link = trimBeginningAndEndingSlashes(link); String[] parts = StringUtils.split(link, "/"); if (parts.length != 2) { return false; } if (StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (StringUtils.isEmpty(parts[1])) { return false; } return true; } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static Map<String, String> paramEncode(Map<String, String> queryParams) { HashMap<String, String> map = new HashMap<>(); for(Map.Entry<String, String> paramEntry: queryParams.entrySet()) { try { map.put(paramEntry.getKey(), URLEncoder.encode(paramEntry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } return map; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static Boolean isCollectionPartitioned(DocumentCollection collection) { if (collection == null) { throw new IllegalArgumentException("collection"); } return collection.getPartitionKey() != null && collection.getPartitionKey().getPaths() != null && collection.getPartitionKey().getPaths().size() > 0; } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } public static boolean isFeedRequest(OperationType requestOperationType) { return requestOperationType == OperationType.Create || requestOperationType == OperationType.Upsert || requestOperationType == OperationType.ReadFeed || requestOperationType == OperationType.Query || requestOperationType == OperationType.SqlQuery || requestOperationType == OperationType.HeadFeed; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.SDK_VERSION); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = osName.replaceAll("\\s", ""); String userAgent = String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); return userAgent; } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String zonedDateTimeAsUTCRFC1123(OffsetDateTime offsetDateTime){ return Utils.RFC_1123_DATE_TIME.format(offsetDateTime.atZoneSameInstant(GMT_ZONE_ID)); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val.intValue() : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <V> List<V> immutableListOf(V v1) { List<V> list = new ArrayList<>(); list.add(v1); return Collections.unmodifiableList(list); } public static <K, V> Map<K, V>immutableMapOf() { return Collections.emptyMap(); } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<K ,V>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<T>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static ByteBuffer toByteBuffer(byte[] bytes) { return ByteBuffer.wrap(bytes); } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static byte[] serializeObjectToByteArray(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
Done
private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { return version; } }
private static int getJavaVersion() { int version = -1; try { String completeJavaVersion = System.getProperty("java.version"); String[] versionElements = completeJavaVersion.split("\\."); int versionFirstPart = Integer.parseInt(versionElements[0]); if (versionFirstPart == 1) { version = Integer.parseInt(versionElements[1]); } else { version = versionFirstPart; } return version; } catch (Exception ex) { logger.warn("Error while fetching java version", ex); return version; } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); public static final Base64.Decoder Base64UrlDecoder = Base64.getUrlDecoder(); private static final ObjectMapper simpleObjectMapper = new ObjectMapper(); private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); static { Utils.simpleObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); Utils.simpleObjectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); int javaVersion = getJavaVersion(); if (javaVersion != -1 && javaVersion < 16) { Utils.simpleObjectMapper.registerModule(new AfterburnerModule()); } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUtf16Bytes(String str) { return str.getBytes(StandardCharsets.UTF_16LE); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } /** * Checks whether the specified link is Name based or not * * @param link the link to analyze. * @return true or false */ public static boolean isNameBased(String link) { if (StringUtils.isEmpty(link)) { return false; } if (link.startsWith("/") && link.length() > 1) { link = link.substring(1); } String[] parts = StringUtils.split(link, "/"); if (parts.length == 0 || StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (parts.length < 2 || StringUtils.isEmpty(parts[1])) { return false; } String databaseID = parts[1]; if (databaseID.length() != 8) { return true; } byte[] buffer = ResourceId.fromBase64String(databaseID); if (buffer.length != 4) { return true; } return false; } /** * Checks whether the specified link is a Database Self Link or a Database * ID based link * * @param link the link to analyze. * @return true or false */ public static boolean isDatabaseLink(String link) { if (StringUtils.isEmpty(link)) { return false; } link = trimBeginningAndEndingSlashes(link); String[] parts = StringUtils.split(link, "/"); if (parts.length != 2) { return false; } if (StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (StringUtils.isEmpty(parts[1])) { return false; } return true; } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static Map<String, String> paramEncode(Map<String, String> queryParams) { HashMap<String, String> map = new HashMap<>(); for(Map.Entry<String, String> paramEntry: queryParams.entrySet()) { try { map.put(paramEntry.getKey(), URLEncoder.encode(paramEntry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } return map; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static Boolean isCollectionPartitioned(DocumentCollection collection) { if (collection == null) { throw new IllegalArgumentException("collection"); } return collection.getPartitionKey() != null && collection.getPartitionKey().getPaths() != null && collection.getPartitionKey().getPaths().size() > 0; } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } public static boolean isFeedRequest(OperationType requestOperationType) { return requestOperationType == OperationType.Create || requestOperationType == OperationType.Upsert || requestOperationType == OperationType.ReadFeed || requestOperationType == OperationType.Query || requestOperationType == OperationType.SqlQuery || requestOperationType == OperationType.HeadFeed; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.SDK_VERSION); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = osName.replaceAll("\\s", ""); String userAgent = String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); return userAgent; } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String zonedDateTimeAsUTCRFC1123(OffsetDateTime offsetDateTime){ return Utils.RFC_1123_DATE_TIME.format(offsetDateTime.atZoneSameInstant(GMT_ZONE_ID)); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val.intValue() : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <V> List<V> immutableListOf(V v1) { List<V> list = new ArrayList<>(); list.add(v1); return Collections.unmodifiableList(list); } public static <K, V> Map<K, V>immutableMapOf() { return Collections.emptyMap(); } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<K ,V>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<T>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static ByteBuffer toByteBuffer(byte[] bytes) { return ByteBuffer.wrap(bytes); } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static byte[] serializeObjectToByteArray(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static final int ONE_KB = 1024; private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); public static final Base64.Encoder Base64UrlEncoder = Base64.getUrlEncoder(); public static final Base64.Decoder Base64UrlDecoder = Base64.getUrlDecoder(); private static final ObjectMapper simpleObjectMapper = new ObjectMapper(); private static final TimeBasedGenerator TIME_BASED_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); private static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); static { Utils.simpleObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); Utils.simpleObjectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); Utils.simpleObjectMapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false); int javaVersion = getJavaVersion(); if (javaVersion != -1 && javaVersion < 16) { Utils.simpleObjectMapper.registerModule(new AfterburnerModule()); } } public static byte[] getUTF8BytesOrNull(String str) { if (str == null) { return null; } return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUTF8Bytes(String str) { return str.getBytes(StandardCharsets.UTF_8); } public static byte[] getUtf16Bytes(String str) { return str.getBytes(StandardCharsets.UTF_16LE); } public static String encodeBase64String(byte[] binaryData) { String encodedString = Base64Encoder.encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } public static String decodeBase64String(String encodedString) { byte[] decodeString = Base64Decoder.decode(encodedString); return new String(decodeString, StandardCharsets.UTF_8); } public static String decodeAsUTF8String(String inputString) { if (inputString == null || inputString.isEmpty()) { return inputString; } try { return URLDecoder.decode(inputString, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { logger.warn("Error while decoding input string", e); return inputString; } } public static String encodeUrlBase64String(byte[] binaryData) { String encodedString = Base64UrlEncoder.withoutPadding().encodeToString(binaryData); if (encodedString.endsWith("\r\n")) { encodedString = encodedString.substring(0, encodedString.length() - 2); } return encodedString; } /** * Checks whether the specified link is Name based or not * * @param link the link to analyze. * @return true or false */ public static boolean isNameBased(String link) { if (StringUtils.isEmpty(link)) { return false; } if (link.startsWith("/") && link.length() > 1) { link = link.substring(1); } String[] parts = StringUtils.split(link, "/"); if (parts.length == 0 || StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (parts.length < 2 || StringUtils.isEmpty(parts[1])) { return false; } String databaseID = parts[1]; if (databaseID.length() != 8) { return true; } byte[] buffer = ResourceId.fromBase64String(databaseID); if (buffer.length != 4) { return true; } return false; } /** * Checks whether the specified link is a Database Self Link or a Database * ID based link * * @param link the link to analyze. * @return true or false */ public static boolean isDatabaseLink(String link) { if (StringUtils.isEmpty(link)) { return false; } link = trimBeginningAndEndingSlashes(link); String[] parts = StringUtils.split(link, "/"); if (parts.length != 2) { return false; } if (StringUtils.isEmpty(parts[0]) || !parts[0].equalsIgnoreCase(Paths.DATABASES_PATH_SEGMENT)) { return false; } if (StringUtils.isEmpty(parts[1])) { return false; } return true; } /** * Joins the specified paths by appropriately padding them with '/' * * @param path1 the first path segment to join. * @param path2 the second path segment to join. * @return the concatenated path with '/' */ public static String joinPath(String path1, String path2) { path1 = trimBeginningAndEndingSlashes(path1); String result = "/" + path1 + "/"; if (!StringUtils.isEmpty(path2)) { path2 = trimBeginningAndEndingSlashes(path2); result += path2 + "/"; } return result; } /** * Trims the beginning and ending '/' from the given path * * @param path the path to trim for beginning and ending slashes * @return the path without beginning and ending '/' */ public static String trimBeginningAndEndingSlashes(String path) { if(path == null) { return null; } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } public static Map<String, String> paramEncode(Map<String, String> queryParams) { HashMap<String, String> map = new HashMap<>(); for(Map.Entry<String, String> paramEntry: queryParams.entrySet()) { try { map.put(paramEntry.getKey(), URLEncoder.encode(paramEntry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } return map; } public static String createQuery(Map<String, String> queryParameters) { if (queryParameters == null) return ""; StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> nameValuePair : queryParameters.entrySet()) { String key = nameValuePair.getKey(); String value = nameValuePair.getValue(); if (key != null && !key.isEmpty()) { if (queryString.length() > 0) { queryString.append(RuntimeConstants.Separators.Query[1]); } queryString.append(key); if (value != null) { queryString.append(RuntimeConstants.Separators.Query[2]); queryString.append(value); } } } return queryString.toString(); } public static URI setQuery(String urlString, String query) { if (urlString == null) throw new IllegalStateException("urlString parameter can't be null."); query = Utils.removeLeadingQuestionMark(query); try { if (query != null && !query.isEmpty()) { return new URI(Utils.addTrailingSlash(urlString) + RuntimeConstants.Separators.Query[0] + query); } else { return new URI(Utils.addTrailingSlash(urlString)); } } catch (URISyntaxException e) { throw new IllegalStateException("Uri is invalid: ", e); } } /** * Given the full path to a resource, extract the collection path. * * @param resourceFullName the full path to the resource. * @return the path of the collection in which the resource is. */ public static String getCollectionName(String resourceFullName) { if (resourceFullName != null) { resourceFullName = Utils.trimBeginningAndEndingSlashes(resourceFullName); int slashCount = 0; for (int i = 0; i < resourceFullName.length(); i++) { if (resourceFullName.charAt(i) == '/') { slashCount++; if (slashCount == 4) { return resourceFullName.substring(0, i); } } } } return resourceFullName; } public static <T> int getCollectionSize(Collection<T> collection) { if (collection == null) { return 0; } return collection.size(); } public static Boolean isCollectionPartitioned(DocumentCollection collection) { if (collection == null) { throw new IllegalArgumentException("collection"); } return collection.getPartitionKey() != null && collection.getPartitionKey().getPaths() != null && collection.getPartitionKey().getPaths().size() > 0; } public static boolean isCollectionChild(ResourceType type) { return type == ResourceType.Document || type == ResourceType.Attachment || type == ResourceType.Conflict || type == ResourceType.StoredProcedure || type == ResourceType.Trigger || type == ResourceType.UserDefinedFunction; } public static boolean isWriteOperation(OperationType operationType) { return operationType == OperationType.Create || operationType == OperationType.Upsert || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.ExecuteJavaScript || operationType == OperationType.Batch; } public static boolean isFeedRequest(OperationType requestOperationType) { return requestOperationType == OperationType.Create || requestOperationType == OperationType.Upsert || requestOperationType == OperationType.ReadFeed || requestOperationType == OperationType.Query || requestOperationType == OperationType.SqlQuery || requestOperationType == OperationType.HeadFeed; } private static String addTrailingSlash(String path) { if (path == null || path.isEmpty()) path = new String(RuntimeConstants.Separators.Url); else if (path.charAt(path.length() - 1) != RuntimeConstants.Separators.Url[0]) path = path + RuntimeConstants.Separators.Url[0]; return path; } private static String removeLeadingQuestionMark(String path) { if (path == null || path.isEmpty()) return path; if (path.charAt(0) == RuntimeConstants.Separators.Query[0]) return path.substring(1); return path; } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, ConsistencyLevel desiredConsistency) { switch (backendConsistency) { case STRONG: return desiredConsistency == ConsistencyLevel.STRONG || desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case BOUNDED_STALENESS: return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; case SESSION: case EVENTUAL: case CONSISTENT_PREFIX: return desiredConsistency == ConsistencyLevel.SESSION || desiredConsistency == ConsistencyLevel.EVENTUAL || desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; default: throw new IllegalArgumentException("backendConsistency"); } } public static String getUserAgent() { return getUserAgent(HttpConstants.Versions.SDK_NAME, HttpConstants.Versions.SDK_VERSION); } public static String getUserAgent(String sdkName, String sdkVersion) { String osName = System.getProperty("os.name"); if (osName == null) { osName = "Unknown"; } osName = osName.replaceAll("\\s", ""); String userAgent = String.format("%s%s/%s %s/%s JRE/%s", UserAgentContainer.AZSDK_USERAGENT_PREFIX, sdkName, sdkVersion, osName, System.getProperty("os.version"), System.getProperty("java.version") ); return userAgent; } public static ObjectMapper getSimpleObjectMapper() { return Utils.simpleObjectMapper; } /** * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. * * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); return Utils.RFC_1123_DATE_TIME.format(now); } public static UUID randomUUID() { return TIME_BASED_GENERATOR.generate(); } public static String zonedDateTimeAsUTCRFC1123(OffsetDateTime offsetDateTime){ return Utils.RFC_1123_DATE_TIME.format(offsetDateTime.atZoneSameInstant(GMT_ZONE_ID)); } public static String instantAsUTCRFC1123(Instant instant){ return Utils.RFC_1123_DATE_TIME.format(instant.atZone(GMT_ZONE_ID)); } public static int getValueOrDefault(Integer val, int defaultValue) { return val != null ? val.intValue() : defaultValue; } public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); if (t != null) { throw t; } } public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); if (t != null) { throw t; } } public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); if (t != null) { throw t; } } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (val != null) { return null; } return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String message) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, message)); } public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { if (value) { return null; } return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); } @SuppressWarnings("unchecked") public static <O, I> O as(I i, Class<O> klass) { if (i == null) { return null; } if (klass.isInstance(i)) { return (O) i; } else { return null; } } @SuppressWarnings("unchecked") public static <V> List<V> immutableListOf() { return Collections.EMPTY_LIST; } public static <V> List<V> immutableListOf(V v1) { List<V> list = new ArrayList<>(); list.add(v1); return Collections.unmodifiableList(list); } public static <K, V> Map<K, V>immutableMapOf() { return Collections.emptyMap(); } public static <K, V> Map<K, V>immutableMapOf(K k1, V v1) { Map<K, V> map = new HashMap<K ,V>(); map.put(k1, v1); map = Collections.unmodifiableMap(map); return map; } public static <V> V firstOrDefault(List<V> list) { return list.size() > 0? list.get(0) : null ; } public static class ValueHolder<V> { public ValueHolder() { } public ValueHolder(V v) { this.v = v; } public V v; public static <T> ValueHolder<T> initialize(T v) { return new ValueHolder<T>(v); } } public static <K, V> boolean tryGetValue(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.get(key); return holder.v != null; } public static <K, V> boolean tryRemove(Map<K, V> dictionary, K key, ValueHolder<V> holder) { holder.v = dictionary.remove(key); return holder.v != null; } public static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { if (StringUtils.isEmpty(itemResponseBodyAsString)) { return null; } try { return getSimpleObjectMapper().readValue(itemResponseBodyAsString, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType) { if (Utils.isEmpty(item)) { return null; } try { return getSimpleObjectMapper().readValue(item, itemClassType); } catch (IOException e) { throw new IllegalStateException( String.format("Failed to parse byte-array %s to POJO.", Arrays.toString(item)), e); } } public static <T> T parse(byte[] item, Class<T> itemClassType, ItemDeserializer itemDeserializer) { if (Utils.isEmpty(item)) { return null; } if (itemDeserializer == null) { return Utils.parse(item, itemClassType); } return itemDeserializer.parseFrom(itemClassType, item); } public static ByteBuffer serializeJsonToByteBuffer(ObjectMapper objectMapper, Object object) { try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); objectMapper.writeValue(byteBufferOutputStream, object); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { throw new IllegalArgumentException("Failed to serialize the object into json", e); } } public static boolean isEmpty(byte[] bytes) { return bytes == null || bytes.length == 0; } public static String utf8StringFromOrNull(byte[] bytes) { if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } public static void setContinuationTokenAndMaxItemCount(CosmosPagedFluxOptions pagedFluxOptions, CosmosQueryRequestOptions cosmosQueryRequestOptions) { if (pagedFluxOptions == null) { return; } if (pagedFluxOptions.getRequestContinuation() != null) { ModelBridgeInternal.setQueryRequestOptionsContinuationToken(cosmosQueryRequestOptions, pagedFluxOptions.getRequestContinuation()); } if (pagedFluxOptions.getMaxItemCount() != null) { ModelBridgeInternal.setQueryRequestOptionsMaxItemCount(cosmosQueryRequestOptions, pagedFluxOptions.getMaxItemCount()); } } public static CosmosChangeFeedRequestOptions getEffectiveCosmosChangeFeedRequestOptions( CosmosPagedFluxOptions pagedFluxOptions, CosmosChangeFeedRequestOptions cosmosChangeFeedRequestRequestOptions) { checkNotNull( cosmosChangeFeedRequestRequestOptions, "Argument 'cosmosChangeFeedRequestRequestOptions' must not be null"); return ModelBridgeInternal .getEffectiveChangeFeedRequestOptions( cosmosChangeFeedRequestRequestOptions, pagedFluxOptions); } static String escapeNonAscii(String partitionKeyJson) { StringBuilder sb = null; for (int i = 0; i < partitionKeyJson.length(); i++) { int val = partitionKeyJson.charAt(i); if (val > 127) { if (sb == null) { sb = new StringBuilder(partitionKeyJson.length()); sb.append(partitionKeyJson, 0, i); } sb.append("\\u").append(String.format("%04X", val)); } else { if (sb != null) { sb.append(partitionKeyJson.charAt(i)); } } } if (sb == null) { return partitionKeyJson; } else { return sb.toString(); } } public static byte[] toByteArray(ByteBuf buf) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; } public static ByteBuffer toByteBuffer(byte[] bytes) { return ByteBuffer.wrap(bytes); } public static String toJson(ObjectMapper mapper, ObjectNode object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to convert JSON to STRING", e); } } public static byte[] serializeObjectToByteArray(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static long getMaxIntegratedCacheStalenessInMillis(DedicatedGatewayRequestOptions dedicatedGatewayRequestOptions) { Duration maxIntegratedCacheStaleness = dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness(); if (maxIntegratedCacheStaleness.toNanos() > 0 && maxIntegratedCacheStaleness.toMillis() <= 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness granularity is milliseconds"); } if (maxIntegratedCacheStaleness.toMillis() < 0) { throw new IllegalArgumentException("MaxIntegratedCacheStaleness duration cannot be negative"); } return maxIntegratedCacheStaleness.toMillis(); } }
I'm not familiar with the java tests, but I assume we would want some sort of test timeout here, should the `getStatus()` call fail to be cancelled.
public void cancelHealthcareLro(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); }); }
while (!LongRunningOperationStatus.USER_CANCELLED.equals(operationStatus)) {
public void cancelHealthcareLro(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); }); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private TextAnalyticsAsyncClient getTextAnalyticsAsyncClient(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { return getTextAnalyticsAsyncClientBuilder(httpClient, serviceVersion).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); 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); 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); 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); 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); 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); 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); 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); emptyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that detectLanguage returns an "UNKNOWN" result when faulty text is passed. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .assertNext(response -> validatePrimaryLanguage(getUnknownDetectedLanguage(), response)) .verifyComplete()); } /** * 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); 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); 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); 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); 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); 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); 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 recognizeEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); recognizeCategorizedEntityDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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); 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); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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); 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); 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); 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 recognizePiiEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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 recognizePiiEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); recognizeBatchPiiEntityDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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 @Disabled("https: public void recognizePiiEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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 recognizeLinkedEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); recognizeBatchLinkedEntityDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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 @Disabled("https: public void recognizeLinkedEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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); 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); 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); 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); extractKeyPhrasesForSingleTextInputRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesCollection -> validateKeyPhrases(asList("Bonjour", "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); 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 extractKeyPhrasesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); extractBatchKeyPhrasesDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); emptyTextRunner(document -> StepVerifier.create(client.analyzeSentiment(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } /** * Test analyzing sentiment for a faulty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment("!", TextSentiment.NEUTRAL, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 1); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment("@ new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 1); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 4); final DocumentSentiment expectedDocumentSentiment = new DocumentSentiment( TextSentiment.NEUTRAL, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); StepVerifier.create(client.analyzeSentiment(input)) .assertNext(response -> validateDocumentSentiment(false, expectedDocumentSentiment, response)) .verifyComplete(); }); } /** * 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); analyzeBatchSentimentDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzeSentimentBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 @Disabled("https: public void healthcareLroPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 @Disabled("https: public void healthcareLroWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); healthcareLroRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); 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 healthcareLroEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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 @Disabled("https: public void analyzeHealthcareEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 @Disabled("https: public void analyzeHealthcareEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(Collections.emptyList()) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithMultiSameKindActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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()); assertEquals(2, actionsResult.getExtractSummaryResults().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); 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()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getExtractSummaryResults().stream() .collect(Collectors.toList()).get(0).getActionName()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithCategoriesFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForCategoriesFilter(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzePiiEntityRecognitionWithDomainFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForDomainFilter(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("Linked entity recognition action doesn't contains bingId property. https: public void analyzeLinkedEntityActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(Collections.emptyList()), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollection(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )), 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); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), 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); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getExpectedBatchTextSentiment(), null))), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); }); } @Disabled("Service returned response has unstable value. https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); analyzeExtractSummaryRunner((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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExtractSummaryActionResult(false, null, TIME_NOW, getExpectedExtractSummaryResultCollection(getExpectedExtractSummaryResultSortByOffset()), 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); analyzeExtractSummaryRunner((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); analyzeExtractSummaryRunner((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); analyzeExtractSummaryRunner((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); analyzeExtractSummaryRunner((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); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { analyzeExtractSummaryRunner( (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); } } @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); 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 singleCategoryClassifyAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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.getSingleCategoryClassifyResults().forEach( customSingleCategoryActionResult -> customSingleCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateCustomSingleCategory(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); 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.getMultiCategoryClassifyResults().forEach( customMultiCategoryActionResult -> customMultiCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateCustomMultiCategory(documentResult)))); }); } }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private TextAnalyticsAsyncClient getTextAnalyticsAsyncClient(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { return getTextAnalyticsAsyncClientBuilder(httpClient, serviceVersion).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); 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); 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); 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); 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); 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); 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); 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); emptyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that detectLanguage returns an "UNKNOWN" result when faulty text is passed. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .assertNext(response -> validatePrimaryLanguage(getUnknownDetectedLanguage(), response)) .verifyComplete()); } /** * 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); 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); 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); 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); 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); 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); 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 recognizeEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); recognizeCategorizedEntityDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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); 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); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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); 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); 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); 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 recognizePiiEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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 recognizePiiEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); recognizeBatchPiiEntityDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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 @Disabled("https: public void recognizePiiEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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 recognizeLinkedEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); recognizeBatchLinkedEntityDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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 @Disabled("https: public void recognizeLinkedEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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); 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); 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); 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); extractKeyPhrasesForSingleTextInputRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesCollection -> validateKeyPhrases(asList("Bonjour", "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); 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 extractKeyPhrasesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); extractBatchKeyPhrasesDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); emptyTextRunner(document -> StepVerifier.create(client.analyzeSentiment(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } /** * Test analyzing sentiment for a faulty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); faultyTextRunner(input -> { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment("!", TextSentiment.NEUTRAL, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 1); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment("@ new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 1); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 4); final DocumentSentiment expectedDocumentSentiment = new DocumentSentiment( TextSentiment.NEUTRAL, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); StepVerifier.create(client.analyzeSentiment(input)) .assertNext(response -> validateDocumentSentiment(false, expectedDocumentSentiment, response)) .verifyComplete(); }); } /** * 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); analyzeBatchSentimentDuplicateIdRunner(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); textAnalyticsInputEmptyIdRunner(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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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); 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()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzeSentimentBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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 ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 @Disabled("https: public void healthcareLroPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 @Disabled("https: public void healthcareLroWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); healthcareLroRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); 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 healthcareLroEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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 @Disabled("https: public void analyzeHealthcareEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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 @Disabled("https: public void analyzeHealthcareEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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); 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); 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()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(Collections.emptyList()) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithMultiSameKindActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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()); assertEquals(2, actionsResult.getExtractSummaryResults().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); 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()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getExtractSummaryResults().stream() .collect(Collectors.toList()).get(0).getActionName()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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); 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); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithCategoriesFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForCategoriesFilter(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzePiiEntityRecognitionWithDomainFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForDomainFilter(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("Linked entity recognition action doesn't contains bingId property. https: public void analyzeLinkedEntityActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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(Collections.emptyList()), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollection(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )), 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); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()))), 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); 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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getExpectedBatchTextSentiment(), null))), IterableStream.of(Collections.emptyList()))), result.toStream().collect(Collectors.toList())); }); } @Disabled("Service returned response has unstable value. https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); analyzeExtractSummaryRunner((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(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()), IterableStream.of(asList(getExtractSummaryActionResult(false, null, TIME_NOW, getExpectedExtractSummaryResultCollection(getExpectedExtractSummaryResultSortByOffset()), 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); analyzeExtractSummaryRunner((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); analyzeExtractSummaryRunner((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); analyzeExtractSummaryRunner((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); analyzeExtractSummaryRunner((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); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { analyzeExtractSummaryRunner( (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); } } @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); 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 singleCategoryClassifyAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion); 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.getSingleCategoryClassifyResults().forEach( customSingleCategoryActionResult -> customSingleCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateCustomSingleCategory(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); 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.getMultiCategoryClassifyResults().forEach( customMultiCategoryActionResult -> customMultiCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateCustomMultiCategory(documentResult)))); }); } }
We should include the link to OData documentation on escaping here.
private String escapeSingleQuotes(String input) { if (input == null) { return null; } return input.replace("'", "''"); }
return input.replace("'", "''");
private String escapeSingleQuotes(String input) { if (input == null) { return null; } return input.replace("'", "''"); }
class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } }
class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } }
nit : starting bracket in same line with if if (this.apiType != null) {
private Mono<RxDocumentServiceRequest> populateHeaders(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); } 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 Mono<RxDocumentServiceRequest> populateHeaders(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()); } 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); }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); 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 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 RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private string apiType; 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; 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, string apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); 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, string apiType) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); 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, string apiType) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); 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, string apiType) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.getAndDecrement(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); 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()); 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 = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE)); this.apiType = apiType; } 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); } 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.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); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } clientTelemetry = new ClientTelemetry(null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this); clientTelemetry.init(); this.queryPlanCache = new ConcurrentHashMap<>(); } 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.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled ); 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) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withRequestTimeout(this.connectionPolicy.getRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, false ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @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 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 extends Resource> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID activityId = 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, activityId), invalidPartitionExceptionRetryPolicy); } private <T extends Resource> 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 PipelinedDocumentQueryExecutionContext) { queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return 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; }); }); } @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 populateHeaders(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 populateHeaders(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 populateHeaders(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 populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeaders(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( InternalObjectNode 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(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); 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 (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; } 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, resourceName, this.resolveCosmosResourceType(resourceType), 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 populateHeaders(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 populateHeaders(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 populateHeaders(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) { populateHeaders(request, RequestVerb.PATCH); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(request).processMessage(request); } @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 -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); 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 -> 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(); 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 (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 -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @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 (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 (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); return requestObs.flatMap(req -> { 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 Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options); } @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) { throw 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) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { 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; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); 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())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); 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; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), 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 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) { 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); } @Override public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options); } 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 Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document); } @Override public Flux<FeedResponse<Document>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, Document.class, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public Flux<FeedResponse<Document>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options) { 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) { throw 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) { throw 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()), Document.class, 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>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting 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, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @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); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting 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>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting 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, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @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 extends Resource> 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; 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); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)), this.resetSessionTokenRetryPolicy.getRequestPolicy()); return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, 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); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } 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; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeaders(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)) { 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) { 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); } 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) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } 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) { throw 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(RxDocumentClientImpl::toFeedRanges); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { throw new IllegalStateException("PartitionKeyRange list cannot be null"); } 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 static final AtomicInteger activeClientsCnt = new AtomicInteger(0); 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 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 RxStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private ApiType apiType; 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; 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) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); 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) { this(serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); 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) { this(serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType); 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) { activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.getAndDecrement(); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); 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()); 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 = Collections.synchronizedMap(new SizeLimitingLRUCache(Constants.QUERYPLAN_CACHE_SIZE)); this.apiType = apiType; } 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); } 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.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); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } clientTelemetry = new ClientTelemetry(null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.reactorHttpClient, connectionPolicy.isClientTelemetryEnabled(), this); clientTelemetry.init(); this.queryPlanCache = new ConcurrentHashMap<>(); } 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.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled ); 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) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withRequestTimeout(this.connectionPolicy.getRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, false ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public URI getWriteEndpoint() { return globalEndpointManager.getWriteEndpoints().stream().findFirst().orElse(null); } @Override public URI getReadEndpoint() { return globalEndpointManager.getReadEndpoints().stream().findFirst().orElse(null); } @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 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 extends Resource> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID activityId = 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, activityId), invalidPartitionExceptionRetryPolicy); } private <T extends Resource> 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 PipelinedDocumentQueryExecutionContext) { queryInfo = ((PipelinedDocumentQueryExecutionContext<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; return 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; }); }); } @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 populateHeaders(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 populateHeaders(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 populateHeaders(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 populateHeaders(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeaders(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( InternalObjectNode 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(); ByteBuffer content = BridgeInternal.serializeJsonToByteBuffer(document, mapper); 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 (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; } 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, resourceName, this.resolveCosmosResourceType(resourceType), 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 populateHeaders(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 populateHeaders(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 populateHeaders(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) { populateHeaders(request, RequestVerb.PATCH); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(request).processMessage(request); } @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 -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); 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 -> 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(); 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 (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 -> replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @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 (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 (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); return requestObs.flatMap(req -> { 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 Flux<FeedResponse<Document>> readDocuments(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options); } @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) { throw 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) { throw new IllegalStateException("Failed to get routing map."); } itemIdentityList .forEach(itemIdentity -> { 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; rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); return createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); 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())); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponse(finalList, headers); 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; if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(entry.getValue(), partitionKeySelector); } else { sqlQuerySpec = createReadManyQuerySpec(entry.getValue(), 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 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) { 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); } @Override public Flux<FeedResponse<Document>> queryDocuments(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options); } 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 Flux<FeedResponse<Document>> queryDocuments(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document); } @Override public Flux<FeedResponse<Document>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<Document> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, Document.class, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public Flux<FeedResponse<Document>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options) { 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) { throw 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) { throw 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()), Document.class, 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>> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in upserting 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, List<Object> procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @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); } } @Override public Mono<ResourceResponse<Trigger>> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in upserting 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>> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in upserting 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, String query, CosmosQueryRequestOptions options) { return queryClientEncryptionKeys(databaseLink, new SqlQuerySpec(query), options); } @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 extends Resource> 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; 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); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)), this.resetSessionTokenRetryPolicy.getRequestPolicy()); return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, 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); } @Override public DatabaseAccount getLatestDatabaseAccount() { return this.globalEndpointManager.getLatestDatabaseAccount(); } 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; } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeaders(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)) { 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) { 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); } 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) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } 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) { throw 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(RxDocumentClientImpl::toFeedRanges); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { throw new IllegalStateException("PartitionKeyRange list cannot be null"); } 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()); } }
apiType -> accessor
public static CosmosClientBuilderAccessor getCosmosClientBuilderAccessor() { if (accessor == null) { throw new IllegalStateException("CosmosClientBuilder apiType is not initialized yet!"); } return accessor; }
throw new IllegalStateException("CosmosClientBuilder apiType is not initialized yet!");
public static CosmosClientBuilderAccessor getCosmosClientBuilderAccessor() { if (accessor == null) { throw new IllegalStateException("CosmosClientBuilder accessor is not initialized yet!"); } return accessor; }
class CosmosClientBuilderHelper { private static CosmosClientBuilderAccessor accessor; private CosmosClientBuilderHelper() {} static { ensureClassLoaded(CosmosClientBuilder.class); } public static void setCosmosClientBuilderAccessor(final CosmosClientBuilderAccessor newAccessor) { if (accessor != null) { throw new IllegalStateException("CosmosClientBuilder accessor already initialized!"); } accessor = newAccessor; } public interface CosmosClientBuilderAccessor { void setCosmosClientMetadataCachesSnapshot(CosmosClientBuilder builder, CosmosClientMetadataCachesSnapshot metadataCache); CosmosClientMetadataCachesSnapshot getCosmosClientMetadataCachesSnapshot(CosmosClientBuilder builder); void setCosmosClientApiType(CosmosClientBuilder builder, ApiType apiType); ApiType getCosmosClientApiType(CosmosClientBuilder builder); } }
class CosmosClientBuilderHelper { private static CosmosClientBuilderAccessor accessor; private CosmosClientBuilderHelper() {} static { ensureClassLoaded(CosmosClientBuilder.class); } public static void setCosmosClientBuilderAccessor(final CosmosClientBuilderAccessor newAccessor) { if (accessor != null) { throw new IllegalStateException("CosmosClientBuilder accessor already initialized!"); } accessor = newAccessor; } public interface CosmosClientBuilderAccessor { void setCosmosClientMetadataCachesSnapshot(CosmosClientBuilder builder, CosmosClientMetadataCachesSnapshot metadataCache); CosmosClientMetadataCachesSnapshot getCosmosClientMetadataCachesSnapshot(CosmosClientBuilder builder); void setCosmosClientApiType(CosmosClientBuilder builder, ApiType apiType); ApiType getCosmosClientApiType(CosmosClientBuilder builder); } }
Please use org.assertj.core.api.Assertions.assertThat , that what we are using in other places
public void validateApiTypePresent() { ApiType apiType = ApiType.TABLE; DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(directConnectionConfig) .userAgentSuffix("custom-direct-client") .multipleWriteRegionsEnabled(false) .endpointDiscoveryEnabled(false) .readRequestsFallbackEnabled(true); ImplementationBridgeHelpers.CosmosClientBuilderHelper.CosmosClientBuilderAccessor accessor = ImplementationBridgeHelpers.CosmosClientBuilderHelper.getCosmosClientBuilderAccessor(); accessor.setCosmosClientApiType(cosmosClientBuilder, apiType); RxDocumentClientImpl documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(new CosmosAsyncClient(cosmosClientBuilder)); Assert.assertEquals(ReflectionUtils.getApiType(documentClient), apiType); }
Assert.assertEquals(ReflectionUtils.getApiType(documentClient), apiType);
public void validateApiTypePresent() { ApiType apiType = ApiType.TABLE; DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(directConnectionConfig) .userAgentSuffix("custom-direct-client") .multipleWriteRegionsEnabled(false) .endpointDiscoveryEnabled(false) .readRequestsFallbackEnabled(true); ImplementationBridgeHelpers.CosmosClientBuilderHelper.CosmosClientBuilderAccessor accessor = ImplementationBridgeHelpers.CosmosClientBuilderHelper.getCosmosClientBuilderAccessor(); accessor.setCosmosClientApiType(cosmosClientBuilder, apiType); RxDocumentClientImpl documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(new CosmosAsyncClient(cosmosClientBuilder)); assertThat(ReflectionUtils.getApiType(documentClient)).isEqualTo(apiType); }
class CosmosClientBuilderTest { String hostName = "https: @Test(groups = "unit") public void validateBadPreferredRegions1() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of("westus1,eastus1")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e).hasCauseExactlyInstanceOf(URISyntaxException.class); assertThat(e.getMessage()).isEqualTo("invalid location [westus1,eastus1] or serviceEndpoint [https: } } @Test(groups = "unit") public void validateBadPreferredRegions2() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of(" ")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("preferredRegion can't be empty"); } } @Test(groups = "emulator") }
class CosmosClientBuilderTest { String hostName = "https: @Test(groups = "unit") public void validateBadPreferredRegions1() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of("westus1,eastus1")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e).hasCauseExactlyInstanceOf(URISyntaxException.class); assertThat(e.getMessage()).isEqualTo("invalid location [westus1,eastus1] or serviceEndpoint [https: } } @Test(groups = "unit") public void validateBadPreferredRegions2() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of(" ")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("preferredRegion can't be empty"); } } @Test(groups = "emulator") }
As you are using SQL as default , please pass that in test as well
public void barrierWithAadAuthorizationTokenProviderType() throws URISyntaxException { TokenCredential tokenCredential = new AadSimpleTokenCredential(TestConfigurations.MASTER_KEY); IAuthorizationTokenProvider authTokenProvider = new RxDocumentClientImpl(new URI(TestConfigurations.HOST), null, null, null, null, new Configs(), null, null, tokenCredential, false, false, false, null, ApiType.NONE); ResourceType resourceType = ResourceType.DocumentCollection; OperationType operationType = OperationType.Read; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(authTokenProvider.getAuthorizationTokenType()).isEqualTo(AuthorizationTokenType.AadToken); assertThat(barrierRequest.authorizationTokenType).isEqualTo(AuthorizationTokenType.AadToken); assertThat(request.authorizationTokenType).isEqualTo(AuthorizationTokenType.PrimaryMasterKey); }
ApiType.NONE);
public void barrierWithAadAuthorizationTokenProviderType() throws URISyntaxException { TokenCredential tokenCredential = new AadSimpleTokenCredential(TestConfigurations.MASTER_KEY); IAuthorizationTokenProvider authTokenProvider = new RxDocumentClientImpl(new URI(TestConfigurations.HOST), null, null, null, null, new Configs(), null, null, tokenCredential, false, false, false, null, null); ResourceType resourceType = ResourceType.DocumentCollection; OperationType operationType = OperationType.Read; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(authTokenProvider.getAuthorizationTokenType()).isEqualTo(AuthorizationTokenType.AadToken); assertThat(barrierRequest.authorizationTokenType).isEqualTo(AuthorizationTokenType.AadToken); assertThat(request.authorizationTokenType).isEqualTo(AuthorizationTokenType.PrimaryMasterKey); }
class BarrierRequestHelperTest { @Test(groups = "direct") public void barrierBasic() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); for (ResourceType resourceType : ResourceType.values()) { for (OperationType operationType : OperationType.values()) { Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map<String, String>) null); BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 10l, 10l).block(); request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==", randomResource, null); request.setResourceId("3"); try { BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 10l, 10l).block(); } catch (Exception e) { if (!BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, operationType)) { fail("Should not fail for non-collection head combinations"); } } } } } @Test(groups = "direct") public void barrierDBFeed() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.DocumentCollection; OperationType operationType = OperationType.Query; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.HeadFeed); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.Database); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); } @Test(groups = "direct") public void barrierDocumentQueryNameBasedRequest() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.Document; OperationType operationType = OperationType.Query; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); assertThat(barrierRequest.getResourceAddress()).isEqualTo("dbs/dbname/colls/collname"); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); } @Test(groups = "direct") public void barrierDocumentReadNameBasedRequest() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.Document; OperationType operationType = OperationType.Read; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); assertThat(barrierRequest.getResourceAddress()).isEqualTo("dbs/dbname/colls/collname"); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); assertThat(barrierRequest.getIsNameBased()).isEqualTo(true); } @Test(groups = "direct") public void barrierDocumentReadRidBasedRequest() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.Document; OperationType operationType = OperationType.Read; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, "7mVFAA==", resourceType, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); assertThat(barrierRequest.getResourceAddress()).isEqualTo("7mVFAA=="); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); assertThat(barrierRequest.getIsNameBased()).isEqualTo(false); } @Test(groups = "direct") @DataProvider(name = "isCollectionHeadBarrierRequestArgProvider") public Object[][] isCollectionHeadBarrierRequestArgProvider() { return new Object[][]{ {ResourceType.Attachment, null, true}, {ResourceType.Document, null, true}, {ResourceType.Conflict, null, true}, {ResourceType.StoredProcedure, null, true}, {ResourceType.Attachment, null, true}, {ResourceType.Trigger, null, true}, {ResourceType.DocumentCollection, OperationType.ReadFeed, false}, {ResourceType.DocumentCollection, OperationType.Query, false}, {ResourceType.DocumentCollection, OperationType.SqlQuery, false}, {ResourceType.DocumentCollection, OperationType.Create, true}, {ResourceType.DocumentCollection, OperationType.Read, true}, {ResourceType.DocumentCollection, OperationType.Replace, true}, {ResourceType.DocumentCollection, OperationType.ExecuteJavaScript, true}, {ResourceType.PartitionKeyRange, null, false}, }; } @Test(groups = "direct", dataProvider = "isCollectionHeadBarrierRequestArgProvider") public void isCollectionHeadBarrierRequest(ResourceType resourceType, OperationType operationType, boolean expectedResult) { if (operationType != null) { boolean actual = BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, operationType); assertThat(actual).isEqualTo(expectedResult); } else { for (OperationType type : OperationType.values()) { boolean actual = BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, type); assertThat(actual).isEqualTo(expectedResult); } } } private IAuthorizationTokenProvider getIAuthorizationTokenProvider() { return (RxDocumentClientImpl) new AsyncDocumentClient.Builder() .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withServiceEndpoint(TestConfigurations.HOST) .build(); } private String getHeaderValue(RxDocumentServiceRequest req, String name) { return req.getHeaders().get(name); } private String getPartitionKey(RxDocumentServiceRequest req) { return getHeaderValue(req, HttpConstants.HttpHeaders.PARTITION_KEY); } private String getCollectionRid(RxDocumentServiceRequest req) { return getHeaderValue(req, WFConstants.BackendHeaders.COLLECTION_RID); } private PartitionKeyRangeIdentity getPartitionKeyRangeIdentity(RxDocumentServiceRequest req) { return req.getPartitionKeyRangeIdentity(); } private Long getTargetLsn(RxDocumentServiceRequest req) { return Long.parseLong(getHeaderValue(req, HttpConstants.HttpHeaders.TARGET_LSN)); } private Long getTargetGlobalLsn(RxDocumentServiceRequest req) { return Long.parseLong(getHeaderValue(req, HttpConstants.HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN)); } class AadSimpleTokenCredential implements TokenCredential { private final String keyEncoded; private final String AAD_HEADER_COSMOS_EMULATOR = "{\"typ\":\"JWT\",\"alg\":\"RS256\",\"x5t\":\"CosmosEmulatorPrimaryMaster\",\"kid\":\"CosmosEmulatorPrimaryMaster\"}"; private final String AAD_CLAIM_COSMOS_EMULATOR_FORMAT = "{\"aud\":\"https: public AadSimpleTokenCredential(String emulatorKey) { if (emulatorKey == null || emulatorKey.isEmpty()) { throw new IllegalArgumentException("emulatorKey"); } this.keyEncoded = Utils.encodeUrlBase64String(emulatorKey.getBytes()); } @Override public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) { String aadToken = emulatorKey_based_AAD_String(); return Mono.just(new AccessToken(aadToken, OffsetDateTime.now().plusHours(2))); } String emulatorKey_based_AAD_String() { ZonedDateTime currentTime = ZonedDateTime.now(); String part1Encoded = Utils.encodeUrlBase64String(AAD_HEADER_COSMOS_EMULATOR.getBytes()); String part2 = String.format(AAD_CLAIM_COSMOS_EMULATOR_FORMAT, currentTime.toEpochSecond(), currentTime.toEpochSecond(), currentTime.plusHours(2).toEpochSecond()); String part2Encoded = Utils.encodeUrlBase64String(part2.getBytes()); return part1Encoded + "." + part2Encoded + "." + this.keyEncoded; } } }
class BarrierRequestHelperTest { @Test(groups = "direct") public void barrierBasic() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); for (ResourceType resourceType : ResourceType.values()) { for (OperationType operationType : OperationType.values()) { Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map<String, String>) null); BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 10l, 10l).block(); request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==", randomResource, null); request.setResourceId("3"); try { BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 10l, 10l).block(); } catch (Exception e) { if (!BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, operationType)) { fail("Should not fail for non-collection head combinations"); } } } } } @Test(groups = "direct") public void barrierDBFeed() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.DocumentCollection; OperationType operationType = OperationType.Query; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.HeadFeed); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.Database); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); } @Test(groups = "direct") public void barrierDocumentQueryNameBasedRequest() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.Document; OperationType operationType = OperationType.Query; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); assertThat(barrierRequest.getResourceAddress()).isEqualTo("dbs/dbname/colls/collname"); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); } @Test(groups = "direct") public void barrierDocumentReadNameBasedRequest() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.Document; OperationType operationType = OperationType.Read; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); assertThat(barrierRequest.getResourceAddress()).isEqualTo("dbs/dbname/colls/collname"); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); assertThat(barrierRequest.getIsNameBased()).isEqualTo(true); } @Test(groups = "direct") public void barrierDocumentReadRidBasedRequest() { IAuthorizationTokenProvider authTokenProvider = getIAuthorizationTokenProvider(); ResourceType resourceType = ResourceType.Document; OperationType operationType = OperationType.Read; Document randomResource = new Document(); randomResource.setId(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), operationType, "7mVFAA==", resourceType, (Map<String, String>) null); RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(mockDiagnosticsClientContext(), request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); assertThat(barrierRequest.getResourceAddress()).isEqualTo("7mVFAA=="); assertThat(getTargetGlobalLsn(barrierRequest)).isEqualTo(10l); assertThat(getTargetLsn(barrierRequest)).isEqualTo(11l); assertThat(barrierRequest.getIsNameBased()).isEqualTo(false); } @Test(groups = "direct") @DataProvider(name = "isCollectionHeadBarrierRequestArgProvider") public Object[][] isCollectionHeadBarrierRequestArgProvider() { return new Object[][]{ {ResourceType.Attachment, null, true}, {ResourceType.Document, null, true}, {ResourceType.Conflict, null, true}, {ResourceType.StoredProcedure, null, true}, {ResourceType.Attachment, null, true}, {ResourceType.Trigger, null, true}, {ResourceType.DocumentCollection, OperationType.ReadFeed, false}, {ResourceType.DocumentCollection, OperationType.Query, false}, {ResourceType.DocumentCollection, OperationType.SqlQuery, false}, {ResourceType.DocumentCollection, OperationType.Create, true}, {ResourceType.DocumentCollection, OperationType.Read, true}, {ResourceType.DocumentCollection, OperationType.Replace, true}, {ResourceType.DocumentCollection, OperationType.ExecuteJavaScript, true}, {ResourceType.PartitionKeyRange, null, false}, }; } @Test(groups = "direct", dataProvider = "isCollectionHeadBarrierRequestArgProvider") public void isCollectionHeadBarrierRequest(ResourceType resourceType, OperationType operationType, boolean expectedResult) { if (operationType != null) { boolean actual = BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, operationType); assertThat(actual).isEqualTo(expectedResult); } else { for (OperationType type : OperationType.values()) { boolean actual = BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, type); assertThat(actual).isEqualTo(expectedResult); } } } private IAuthorizationTokenProvider getIAuthorizationTokenProvider() { return (RxDocumentClientImpl) new AsyncDocumentClient.Builder() .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withServiceEndpoint(TestConfigurations.HOST) .build(); } private String getHeaderValue(RxDocumentServiceRequest req, String name) { return req.getHeaders().get(name); } private String getPartitionKey(RxDocumentServiceRequest req) { return getHeaderValue(req, HttpConstants.HttpHeaders.PARTITION_KEY); } private String getCollectionRid(RxDocumentServiceRequest req) { return getHeaderValue(req, WFConstants.BackendHeaders.COLLECTION_RID); } private PartitionKeyRangeIdentity getPartitionKeyRangeIdentity(RxDocumentServiceRequest req) { return req.getPartitionKeyRangeIdentity(); } private Long getTargetLsn(RxDocumentServiceRequest req) { return Long.parseLong(getHeaderValue(req, HttpConstants.HttpHeaders.TARGET_LSN)); } private Long getTargetGlobalLsn(RxDocumentServiceRequest req) { return Long.parseLong(getHeaderValue(req, HttpConstants.HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN)); } class AadSimpleTokenCredential implements TokenCredential { private final String keyEncoded; private final String AAD_HEADER_COSMOS_EMULATOR = "{\"typ\":\"JWT\",\"alg\":\"RS256\",\"x5t\":\"CosmosEmulatorPrimaryMaster\",\"kid\":\"CosmosEmulatorPrimaryMaster\"}"; private final String AAD_CLAIM_COSMOS_EMULATOR_FORMAT = "{\"aud\":\"https: public AadSimpleTokenCredential(String emulatorKey) { if (emulatorKey == null || emulatorKey.isEmpty()) { throw new IllegalArgumentException("emulatorKey"); } this.keyEncoded = Utils.encodeUrlBase64String(emulatorKey.getBytes()); } @Override public Mono<AccessToken> getToken(TokenRequestContext tokenRequestContext) { String aadToken = emulatorKey_based_AAD_String(); return Mono.just(new AccessToken(aadToken, OffsetDateTime.now().plusHours(2))); } String emulatorKey_based_AAD_String() { ZonedDateTime currentTime = ZonedDateTime.now(); String part1Encoded = Utils.encodeUrlBase64String(AAD_HEADER_COSMOS_EMULATOR.getBytes()); String part2 = String.format(AAD_CLAIM_COSMOS_EMULATOR_FORMAT, currentTime.toEpochSecond(), currentTime.toEpochSecond(), currentTime.plusHours(2).toEpochSecond()); String part2Encoded = Utils.encodeUrlBase64String(part2.getBytes()); return part1Encoded + "." + part2Encoded + "." + this.keyEncoded; } } }
also please use static import similar to other tests
public void validateApiTypePresent() { ApiType apiType = ApiType.TABLE; DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(directConnectionConfig) .userAgentSuffix("custom-direct-client") .multipleWriteRegionsEnabled(false) .endpointDiscoveryEnabled(false) .readRequestsFallbackEnabled(true); ImplementationBridgeHelpers.CosmosClientBuilderHelper.CosmosClientBuilderAccessor accessor = ImplementationBridgeHelpers.CosmosClientBuilderHelper.getCosmosClientBuilderAccessor(); accessor.setCosmosClientApiType(cosmosClientBuilder, apiType); RxDocumentClientImpl documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(new CosmosAsyncClient(cosmosClientBuilder)); Assert.assertEquals(ReflectionUtils.getApiType(documentClient), apiType); }
Assert.assertEquals(ReflectionUtils.getApiType(documentClient), apiType);
public void validateApiTypePresent() { ApiType apiType = ApiType.TABLE; DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(directConnectionConfig) .userAgentSuffix("custom-direct-client") .multipleWriteRegionsEnabled(false) .endpointDiscoveryEnabled(false) .readRequestsFallbackEnabled(true); ImplementationBridgeHelpers.CosmosClientBuilderHelper.CosmosClientBuilderAccessor accessor = ImplementationBridgeHelpers.CosmosClientBuilderHelper.getCosmosClientBuilderAccessor(); accessor.setCosmosClientApiType(cosmosClientBuilder, apiType); RxDocumentClientImpl documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(new CosmosAsyncClient(cosmosClientBuilder)); assertThat(ReflectionUtils.getApiType(documentClient)).isEqualTo(apiType); }
class CosmosClientBuilderTest { String hostName = "https: @Test(groups = "unit") public void validateBadPreferredRegions1() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of("westus1,eastus1")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e).hasCauseExactlyInstanceOf(URISyntaxException.class); assertThat(e.getMessage()).isEqualTo("invalid location [westus1,eastus1] or serviceEndpoint [https: } } @Test(groups = "unit") public void validateBadPreferredRegions2() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of(" ")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("preferredRegion can't be empty"); } } @Test(groups = "emulator") }
class CosmosClientBuilderTest { String hostName = "https: @Test(groups = "unit") public void validateBadPreferredRegions1() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of("westus1,eastus1")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e).hasCauseExactlyInstanceOf(URISyntaxException.class); assertThat(e.getMessage()).isEqualTo("invalid location [westus1,eastus1] or serviceEndpoint [https: } } @Test(groups = "unit") public void validateBadPreferredRegions2() { try { CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(hostName) .preferredRegions(ImmutableList.of(" ")) .buildAsyncClient(); client.close(); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e.getMessage()).isEqualTo("preferredRegion can't be empty"); } } @Test(groups = "emulator") }
this requestTimeout is not used by the httpClient (is this expected?), so did not expose the public API.
public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxConnectionPoolSize = DEFAULT_MAX_CONNECTION_POOL_SIZE; this.networkRequestTimeout = DEFAULT_NETWORK_REQUEST_TIMEOUT; }
this.networkRequestTimeout = DEFAULT_NETWORK_REQUEST_TIMEOUT;
public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxConnectionPoolSize = DEFAULT_MAX_CONNECTION_POOL_SIZE; this.networkRequestTimeout = DEFAULT_NETWORK_REQUEST_TIMEOUT; }
class GatewayConnectionConfig { private static final Duration DEFAULT_NETWORK_REQUEST_TIMEOUT = Duration.ofSeconds(5); private static final Duration DEFAULT_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final int DEFAULT_MAX_CONNECTION_POOL_SIZE = 1000; private Duration networkRequestTimeout; private int maxConnectionPoolSize; private Duration idleConnectionTimeout; private ProxyOptions proxy; /** * Constructor. */ /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); } /** * Gets the network request timeout (time to wait for response from network peer). * * @return the network request timeout duration. */ Duration getNetworkRequestTimeout() { return this.networkRequestTimeout; } /** * Sets the network request timeout (time to wait for response from network peer). * The default is 5 seconds. * * @param networkRequestTimeout the network request timeout duration. * @return the {@link GatewayConnectionConfig}. */ GatewayConnectionConfig setNetworkRequestTimeout(Duration networkRequestTimeout) { this.networkRequestTimeout = networkRequestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(ProxyOptions proxy) { if (proxy.getType() != ProxyOptions.Type.HTTP) { throw new IllegalArgumentException("Only http proxy type is supported."); } this.proxy = proxy; return this; } @Override public String toString() { String proxyType = proxy != null ? proxy.getType().toString() : null; String proxyAddress = proxy != null ? proxy.getAddress().toString() : null; return "GatewayConnectionConfig{" + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", networkRequestTimeout=" + networkRequestTimeout + ", proxyType=" + proxyType + ", inetSocketProxyAddress=" + proxyAddress + '}'; } }
class GatewayConnectionConfig { private static final Duration MIN_NETWORK_REQUEST_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_NETWORK_REQUEST_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final int DEFAULT_MAX_CONNECTION_POOL_SIZE = 1000; private Duration networkRequestTimeout; private int maxConnectionPoolSize; private Duration idleConnectionTimeout; private ProxyOptions proxy; /** * Constructor. */ /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); } /** * Gets the network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @return the network request timeout duration. */ Duration getNetworkRequestTimeout() { return this.networkRequestTimeout; } /** * Sets the network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @param networkRequestTimeout the network request timeout duration. * @return the {@link GatewayConnectionConfig}. */ GatewayConnectionConfig setNetworkRequestTimeout(Duration networkRequestTimeout) { checkNotNull(networkRequestTimeout, "NetworkRequestTimeout can not be null"); checkArgument(networkRequestTimeout.toMillis() >= MIN_NETWORK_REQUEST_TIMEOUT.toMillis(), "NetworkRequestTimeout can not be less than %s millis", MIN_NETWORK_REQUEST_TIMEOUT.toMillis()); this.networkRequestTimeout = networkRequestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(ProxyOptions proxy) { if (proxy.getType() != ProxyOptions.Type.HTTP) { throw new IllegalArgumentException("Only http proxy type is supported."); } this.proxy = proxy; return this; } @Override public String toString() { String proxyType = proxy != null ? proxy.getType().toString() : null; String proxyAddress = proxy != null ? proxy.getAddress().toString() : null; return "GatewayConnectionConfig{" + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", networkRequestTimeout=" + networkRequestTimeout + ", proxyType=" + proxyType + ", inetSocketProxyAddress=" + proxyAddress + '}'; } }
Yes we are not using this value anywhere, lets not expose , we can take this item later
public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxConnectionPoolSize = DEFAULT_MAX_CONNECTION_POOL_SIZE; this.networkRequestTimeout = DEFAULT_NETWORK_REQUEST_TIMEOUT; }
this.networkRequestTimeout = DEFAULT_NETWORK_REQUEST_TIMEOUT;
public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxConnectionPoolSize = DEFAULT_MAX_CONNECTION_POOL_SIZE; this.networkRequestTimeout = DEFAULT_NETWORK_REQUEST_TIMEOUT; }
class GatewayConnectionConfig { private static final Duration DEFAULT_NETWORK_REQUEST_TIMEOUT = Duration.ofSeconds(5); private static final Duration DEFAULT_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final int DEFAULT_MAX_CONNECTION_POOL_SIZE = 1000; private Duration networkRequestTimeout; private int maxConnectionPoolSize; private Duration idleConnectionTimeout; private ProxyOptions proxy; /** * Constructor. */ /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); } /** * Gets the network request timeout (time to wait for response from network peer). * * @return the network request timeout duration. */ Duration getNetworkRequestTimeout() { return this.networkRequestTimeout; } /** * Sets the network request timeout (time to wait for response from network peer). * The default is 5 seconds. * * @param networkRequestTimeout the network request timeout duration. * @return the {@link GatewayConnectionConfig}. */ GatewayConnectionConfig setNetworkRequestTimeout(Duration networkRequestTimeout) { this.networkRequestTimeout = networkRequestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(ProxyOptions proxy) { if (proxy.getType() != ProxyOptions.Type.HTTP) { throw new IllegalArgumentException("Only http proxy type is supported."); } this.proxy = proxy; return this; } @Override public String toString() { String proxyType = proxy != null ? proxy.getType().toString() : null; String proxyAddress = proxy != null ? proxy.getAddress().toString() : null; return "GatewayConnectionConfig{" + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", networkRequestTimeout=" + networkRequestTimeout + ", proxyType=" + proxyType + ", inetSocketProxyAddress=" + proxyAddress + '}'; } }
class GatewayConnectionConfig { private static final Duration MIN_NETWORK_REQUEST_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_NETWORK_REQUEST_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final int DEFAULT_MAX_CONNECTION_POOL_SIZE = 1000; private Duration networkRequestTimeout; private int maxConnectionPoolSize; private Duration idleConnectionTimeout; private ProxyOptions proxy; /** * Constructor. */ /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); } /** * Gets the network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @return the network request timeout duration. */ Duration getNetworkRequestTimeout() { return this.networkRequestTimeout; } /** * Sets the network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @param networkRequestTimeout the network request timeout duration. * @return the {@link GatewayConnectionConfig}. */ GatewayConnectionConfig setNetworkRequestTimeout(Duration networkRequestTimeout) { checkNotNull(networkRequestTimeout, "NetworkRequestTimeout can not be null"); checkArgument(networkRequestTimeout.toMillis() >= MIN_NETWORK_REQUEST_TIMEOUT.toMillis(), "NetworkRequestTimeout can not be less than %s millis", MIN_NETWORK_REQUEST_TIMEOUT.toMillis()); this.networkRequestTimeout = networkRequestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(ProxyOptions proxy) { if (proxy.getType() != ProxyOptions.Type.HTTP) { throw new IllegalArgumentException("Only http proxy type is supported."); } this.proxy = proxy; return this; } @Override public String toString() { String proxyType = proxy != null ? proxy.getType().toString() : null; String proxyAddress = proxy != null ? proxy.getAddress().toString() : null; return "GatewayConnectionConfig{" + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", networkRequestTimeout=" + networkRequestTimeout + ", proxyType=" + proxyType + ", inetSocketProxyAddress=" + proxyAddress + '}'; } }
We dont need bridge internal method anymore, as this is public
public ConnectionPolicy(GatewayConnectionConfig gatewayConnectionConfig) { this(ConnectionMode.GATEWAY); this.idleHttpConnectionTimeout = gatewayConnectionConfig.getIdleConnectionTimeout(); this.maxConnectionPoolSize = gatewayConnectionConfig.getMaxConnectionPoolSize(); this.httpNetworkRequestTimeout = BridgeInternal.getNetworkRequestTimeoutFromGatewayConnectionConfig(gatewayConnectionConfig); this.proxy = gatewayConnectionConfig.getProxy(); this.tcpConnectionEndpointRediscoveryEnabled = false; }
this.httpNetworkRequestTimeout = BridgeInternal.getNetworkRequestTimeoutFromGatewayConnectionConfig(gatewayConnectionConfig);
public ConnectionPolicy(GatewayConnectionConfig gatewayConnectionConfig) { this(ConnectionMode.GATEWAY); this.idleHttpConnectionTimeout = gatewayConnectionConfig.getIdleConnectionTimeout(); this.maxConnectionPoolSize = gatewayConnectionConfig.getMaxConnectionPoolSize(); this.httpNetworkRequestTimeout = BridgeInternal.getNetworkRequestTimeoutFromGatewayConnectionConfig(gatewayConnectionConfig); this.proxy = gatewayConnectionConfig.getProxy(); this.tcpConnectionEndpointRediscoveryEnabled = false; }
class ConnectionPolicy { private static final int defaultGatewayMaxConnectionPoolSize = GatewayConnectionConfig.getDefaultConfig() .getMaxConnectionPoolSize(); private ConnectionMode connectionMode; private boolean endpointDiscoveryEnabled; private boolean multipleWriteRegionsEnabled; private List<String> preferredRegions; private boolean readRequestsFallbackEnabled; private ThrottlingRetryOptions throttlingRetryOptions; private String userAgentSuffix; private int maxConnectionPoolSize; private Duration httpNetworkRequestTimeout; private ProxyOptions proxy; private Duration idleHttpConnectionTimeout; private Duration connectTimeout; private Duration idleTcpConnectionTimeout; private Duration idleTcpEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; private Duration tcpNetworkRequestTimeout; private boolean tcpConnectionEndpointRediscoveryEnabled; private boolean clientTelemetryEnabled; /** * Constructor. */ public ConnectionPolicy(DirectConnectionConfig directConnectionConfig) { this(ConnectionMode.DIRECT); this.connectTimeout = directConnectionConfig.getConnectTimeout(); this.idleTcpConnectionTimeout = directConnectionConfig.getIdleConnectionTimeout(); this.idleTcpEndpointTimeout = directConnectionConfig.getIdleEndpointTimeout(); this.maxConnectionsPerEndpoint = directConnectionConfig.getMaxConnectionsPerEndpoint(); this.maxRequestsPerConnection = directConnectionConfig.getMaxRequestsPerConnection(); this.tcpNetworkRequestTimeout = directConnectionConfig.getNetworkRequestTimeout(); this.tcpConnectionEndpointRediscoveryEnabled = directConnectionConfig.isConnectionEndpointRediscoveryEnabled(); } private ConnectionPolicy(ConnectionMode connectionMode) { this.connectionMode = connectionMode; this.endpointDiscoveryEnabled = true; this.maxConnectionPoolSize = defaultGatewayMaxConnectionPoolSize; this.multipleWriteRegionsEnabled = true; this.readRequestsFallbackEnabled = true; this.throttlingRetryOptions = new ThrottlingRetryOptions(); this.userAgentSuffix = ""; } /** * Gets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return {@code true} if Direct TCP connection endpoint rediscovery should is enabled; {@code false} otherwise. */ public boolean isTcpConnectionEndpointRediscoveryEnabled() { return this.tcpConnectionEndpointRediscoveryEnabled; } /** * Sets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return the {@linkplain ConnectionPolicy}. */ public ConnectionPolicy setTcpConnectionEndpointRediscoveryEnabled(boolean tcpConnectionEndpointRediscoveryEnabled) { this.tcpConnectionEndpointRediscoveryEnabled = tcpConnectionEndpointRediscoveryEnabled; return this; } /** * Gets the default connection policy. * * @return the default connection policy. */ public static ConnectionPolicy getDefaultPolicy() { return new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } /** * Gets the http network request timeout (time to wait for response from network peer). * * @return the http request timeout duration. */ public Duration getHttpNetworkRequestTimeout() { return this.httpNetworkRequestTimeout; } /** * Sets the http network request timeout (time to wait for response from network peer). * The default is 5 seconds. * * @param httpNetworkRequestTimeout the http request timeout duration. * @return the ConnectionPolicy. */ public ConnectionPolicy setHttpNetworkRequestTimeout(Duration httpNetworkRequestTimeout) { this.httpNetworkRequestTimeout = httpNetworkRequestTimeout; return this; } /** * Gets the tcp network request timeout (time to wait for response from network peer). * * @return the request timeout duration. */ public Duration getTcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } /** * Sets the tcp network request timeout (time to wait for response from network peer). * The default is 5 seconds. * * @param tcpNetworkRequestTimeout the request timeout duration. * @return the ConnectionPolicy. */ public ConnectionPolicy setTcpNetworkRequestTimeout(Duration tcpNetworkRequestTimeout) { this.tcpNetworkRequestTimeout = tcpNetworkRequestTimeout; return this; } /** * Gets the connection mode used in the client. * * @return the connection mode. */ public ConnectionMode getConnectionMode() { return this.connectionMode; } /** * Sets the connection mode used in the client. * * @param connectionMode the connection mode. * @return the ConnectionPolicy. */ public ConnectionPolicy setConnectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the ConnectionPolicy. */ public ConnectionPolicy setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle http connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleHttpConnectionTimeout() { return this.idleHttpConnectionTimeout; } /** * sets the value of the timeout for an idle http connection. After that time, * the connection will be automatically closed. * * @param idleHttpConnectionTimeout the duration for an idle connection. * @return the ConnectionPolicy. */ public ConnectionPolicy setIdleHttpConnectionTimeout(Duration idleHttpConnectionTimeout) { this.idleHttpConnectionTimeout = idleHttpConnectionTimeout; return this; } /** * Gets the idle tcp connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle tcp connection timeout */ public Duration getIdleTcpConnectionTimeout() { return idleTcpConnectionTimeout; } /** * Sets the idle tcp connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleTcpConnectionTimeout idle connection timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpConnectionTimeout(Duration idleTcpConnectionTimeout) { this.idleTcpConnectionTimeout = idleTcpConnectionTimeout; return this; } /** * Gets the value of user-agent suffix. * * @return the value of user-agent suffix. */ public String getUserAgentSuffix() { return this.userAgentSuffix; } /** * sets the value of the user-agent suffix. * * @param userAgentSuffix The value to be appended to the user-agent header, this is * used for monitoring purposes. * @return the ConnectionPolicy. */ public ConnectionPolicy setUserAgentSuffix(String userAgentSuffix) { this.userAgentSuffix = userAgentSuffix; return this; } /** * Gets the retry policy options associated with the DocumentClient instance. * * @return the RetryOptions instance. */ public ThrottlingRetryOptions getThrottlingRetryOptions() { return this.throttlingRetryOptions; } /** * Sets the retry policy options associated with the DocumentClient instance. * <p> * Properties in the RetryOptions class allow application to customize the built-in * retry policies. This property is optional. When it's not set, the SDK uses the * default values for configuring the retry policies. See RetryOptions class for * more details. * * @param throttlingRetryOptions the RetryOptions instance. * @return the ConnectionPolicy. * @throws IllegalArgumentException thrown if an error occurs */ public ConnectionPolicy setThrottlingRetryOptions(ThrottlingRetryOptions throttlingRetryOptions) { if (throttlingRetryOptions == null) { throw new IllegalArgumentException("retryOptions value must not be null."); } this.throttlingRetryOptions = throttlingRetryOptions; return this; } /** * Gets the flag to enable endpoint discovery for geo-replicated database accounts. * * @return whether endpoint discovery is enabled. */ public boolean isEndpointDiscoveryEnabled() { return this.endpointDiscoveryEnabled; } /** * Sets the flag to enable endpoint discovery for geo-replicated database accounts. * <p> * When EnableEndpointDiscovery is true, the SDK will automatically discover the * current write and read regions to ensure requests are sent to the correct region * based on the capability of the region and the user's preference. * <p> * The default value for this property is true indicating endpoint discovery is enabled. * * @param endpointDiscoveryEnabled true if EndpointDiscovery is enabled. * @return the ConnectionPolicy. */ public ConnectionPolicy setEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) { this.endpointDiscoveryEnabled = endpointDiscoveryEnabled; return this; } /** * Gets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is true indicating that writes are directed to * available writable regions of geo-replicated database account. * * @return flag to enable writes on any regions for geo-replicated database accounts. */ public boolean isMultipleWriteRegionsEnabled() { return this.multipleWriteRegionsEnabled; } /** * Gets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @return flag to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. */ public boolean isReadRequestsFallbackEnabled() { return this.readRequestsFallbackEnabled; } /** * Sets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is false indicating that writes are only directed to * first region in PreferredRegions property. * * @param multipleWriteRegionsEnabled flag to enable writes on any regions for geo-replicated * database accounts. * @return the ConnectionPolicy. */ public ConnectionPolicy setMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) { this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled; return this; } /** * Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @param readRequestsFallbackEnabled flag to enable reads to go to multiple regions configured on an account of * Azure Cosmos DB service. * @return the ConnectionPolicy. */ public ConnectionPolicy setReadRequestsFallbackEnabled(boolean readRequestsFallbackEnabled) { this.readRequestsFallbackEnabled = readRequestsFallbackEnabled; return this; } /** * Gets the preferred regions for geo-replicated database accounts * * @return the list of preferred region. */ public List<String> getPreferredRegions() { return this.preferredRegions != null ? this.preferredRegions : Collections.emptyList(); } /** * Sets the preferred regions for geo-replicated database accounts. For example, * "East US" as the preferred region. * <p> * When EnableEndpointDiscovery is true and PreferredRegions is non-empty, * the SDK will prefer to use the regions in the collection in the order * they are specified to perform operations. * <p> * If EnableEndpointDiscovery is set to false, this property is ignored. * * @param preferredRegions the list of preferred regions. * @return the ConnectionPolicy. */ public ConnectionPolicy setPreferredRegions(List<String> preferredRegions) { this.preferredRegions = preferredRegions; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the ConnectionPolicy. */ public ConnectionPolicy setProxy(ProxyOptions proxy) { this.proxy = proxy; return this; } /** * Gets the direct connect timeout * @return direct connect timeout */ public Duration getConnectTimeout() { return connectTimeout; } /** * Sets the direct connect timeout * @param connectTimeout the connect timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleTcpEndpointTimeout() { return idleTcpEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleTcpEndpointTimeout the idle endpoint timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpEndpointTimeout(Duration idleTcpEndpointTimeout) { this.idleTcpEndpointTimeout = idleTcpEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxConnectionsPerEndpoint the max channels per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per endpoint * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } public boolean isClientTelemetryEnabled() { return clientTelemetryEnabled; } public void setClientTelemetryEnabled(boolean clientTelemetryEnabled) { this.clientTelemetryEnabled = clientTelemetryEnabled; } @Override public String toString() { return "ConnectionPolicy{" + "httpNetworkRequestTimeout=" + httpNetworkRequestTimeout + ", tcpNetworkRequestTimeout=" + tcpNetworkRequestTimeout + ", connectionMode=" + connectionMode + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleHttpConnectionTimeout=" + idleHttpConnectionTimeout + ", idleTcpConnectionTimeout=" + idleTcpConnectionTimeout + ", userAgentSuffix='" + userAgentSuffix + '\'' + ", throttlingRetryOptions=" + throttlingRetryOptions + ", endpointDiscoveryEnabled=" + endpointDiscoveryEnabled + ", preferredRegions=" + preferredRegions + ", multipleWriteRegionsEnabled=" + multipleWriteRegionsEnabled + ", proxyType=" + (proxy != null ? proxy.getType() : null) + ", inetSocketProxyAddress=" + (proxy != null ? proxy.getAddress() : null) + ", readRequestsFallbackEnabled=" + readRequestsFallbackEnabled + ", connectTimeout=" + connectTimeout + ", idleTcpEndpointTimeout=" + idleTcpEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + ", tcpConnectionEndpointRediscoveryEnabled=" + tcpConnectionEndpointRediscoveryEnabled + ", clientTelemetryEnabled=" + clientTelemetryEnabled + '}'; } }
class ConnectionPolicy { private static final int defaultGatewayMaxConnectionPoolSize = GatewayConnectionConfig.getDefaultConfig() .getMaxConnectionPoolSize(); private ConnectionMode connectionMode; private boolean endpointDiscoveryEnabled; private boolean multipleWriteRegionsEnabled; private List<String> preferredRegions; private boolean readRequestsFallbackEnabled; private ThrottlingRetryOptions throttlingRetryOptions; private String userAgentSuffix; private int maxConnectionPoolSize; private Duration httpNetworkRequestTimeout; private ProxyOptions proxy; private Duration idleHttpConnectionTimeout; private Duration connectTimeout; private Duration idleTcpConnectionTimeout; private Duration idleTcpEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; private Duration tcpNetworkRequestTimeout; private boolean tcpConnectionEndpointRediscoveryEnabled; private boolean clientTelemetryEnabled; /** * Constructor. */ public ConnectionPolicy(DirectConnectionConfig directConnectionConfig) { this(ConnectionMode.DIRECT); this.connectTimeout = directConnectionConfig.getConnectTimeout(); this.idleTcpConnectionTimeout = directConnectionConfig.getIdleConnectionTimeout(); this.idleTcpEndpointTimeout = directConnectionConfig.getIdleEndpointTimeout(); this.maxConnectionsPerEndpoint = directConnectionConfig.getMaxConnectionsPerEndpoint(); this.maxRequestsPerConnection = directConnectionConfig.getMaxRequestsPerConnection(); this.tcpNetworkRequestTimeout = directConnectionConfig.getNetworkRequestTimeout(); this.tcpConnectionEndpointRediscoveryEnabled = directConnectionConfig.isConnectionEndpointRediscoveryEnabled(); } private ConnectionPolicy(ConnectionMode connectionMode) { this.connectionMode = connectionMode; this.endpointDiscoveryEnabled = true; this.maxConnectionPoolSize = defaultGatewayMaxConnectionPoolSize; this.multipleWriteRegionsEnabled = true; this.readRequestsFallbackEnabled = true; this.throttlingRetryOptions = new ThrottlingRetryOptions(); this.userAgentSuffix = ""; } /** * Gets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return {@code true} if Direct TCP connection endpoint rediscovery should is enabled; {@code false} otherwise. */ public boolean isTcpConnectionEndpointRediscoveryEnabled() { return this.tcpConnectionEndpointRediscoveryEnabled; } /** * Sets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return the {@linkplain ConnectionPolicy}. */ public ConnectionPolicy setTcpConnectionEndpointRediscoveryEnabled(boolean tcpConnectionEndpointRediscoveryEnabled) { this.tcpConnectionEndpointRediscoveryEnabled = tcpConnectionEndpointRediscoveryEnabled; return this; } /** * Gets the default connection policy. * * @return the default connection policy. */ public static ConnectionPolicy getDefaultPolicy() { return new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } /** * Gets the http network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @return the http request timeout duration. */ public Duration getHttpNetworkRequestTimeout() { return this.httpNetworkRequestTimeout; } /** * Sets the http network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @param httpNetworkRequestTimeout the http request timeout duration. * @return the ConnectionPolicy. */ public ConnectionPolicy setHttpNetworkRequestTimeout(Duration httpNetworkRequestTimeout) { this.httpNetworkRequestTimeout = httpNetworkRequestTimeout; return this; } /** * Gets the tcp network request timeout interval (time to wait for response from network peer). * * Default value is 5 seconds * * @return the network request timeout interval */ public Duration getTcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } /** * Sets the tcp network request timeout interval (time to wait for response from network peer). * * Default value is 5 seconds. * It only allows values &ge;5s and &le;10s. (backend allows requests to take up-to 5 seconds processing time - 5 seconds * buffer so 10 seconds in total for transport is more than sufficient). * * Attention! Please adjust this value with caution. * This config represents the max time allowed to wait for and consume a service response after the request has been written to the network connection. * Setting a value too low can result in having not enough time to wait for the service response - which could cause too aggressive retries and degrade performance. * Setting a value too high can result in fewer retries and reduce chances of success by retries. * * @param tcpNetworkRequestTimeout the network request timeout interval. * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setTcpNetworkRequestTimeout(Duration tcpNetworkRequestTimeout) { this.tcpNetworkRequestTimeout = tcpNetworkRequestTimeout; return this; } /** * Gets the connection mode used in the client. * * @return the connection mode. */ public ConnectionMode getConnectionMode() { return this.connectionMode; } /** * Sets the connection mode used in the client. * * @param connectionMode the connection mode. * @return the ConnectionPolicy. */ public ConnectionPolicy setConnectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the ConnectionPolicy. */ public ConnectionPolicy setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle http connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleHttpConnectionTimeout() { return this.idleHttpConnectionTimeout; } /** * sets the value of the timeout for an idle http connection. After that time, * the connection will be automatically closed. * * @param idleHttpConnectionTimeout the duration for an idle connection. * @return the ConnectionPolicy. */ public ConnectionPolicy setIdleHttpConnectionTimeout(Duration idleHttpConnectionTimeout) { this.idleHttpConnectionTimeout = idleHttpConnectionTimeout; return this; } /** * Gets the idle tcp connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle tcp connection timeout */ public Duration getIdleTcpConnectionTimeout() { return idleTcpConnectionTimeout; } /** * Sets the idle tcp connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleTcpConnectionTimeout idle connection timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpConnectionTimeout(Duration idleTcpConnectionTimeout) { this.idleTcpConnectionTimeout = idleTcpConnectionTimeout; return this; } /** * Gets the value of user-agent suffix. * * @return the value of user-agent suffix. */ public String getUserAgentSuffix() { return this.userAgentSuffix; } /** * sets the value of the user-agent suffix. * * @param userAgentSuffix The value to be appended to the user-agent header, this is * used for monitoring purposes. * @return the ConnectionPolicy. */ public ConnectionPolicy setUserAgentSuffix(String userAgentSuffix) { this.userAgentSuffix = userAgentSuffix; return this; } /** * Gets the retry policy options associated with the DocumentClient instance. * * @return the RetryOptions instance. */ public ThrottlingRetryOptions getThrottlingRetryOptions() { return this.throttlingRetryOptions; } /** * Sets the retry policy options associated with the DocumentClient instance. * <p> * Properties in the RetryOptions class allow application to customize the built-in * retry policies. This property is optional. When it's not set, the SDK uses the * default values for configuring the retry policies. See RetryOptions class for * more details. * * @param throttlingRetryOptions the RetryOptions instance. * @return the ConnectionPolicy. * @throws IllegalArgumentException thrown if an error occurs */ public ConnectionPolicy setThrottlingRetryOptions(ThrottlingRetryOptions throttlingRetryOptions) { if (throttlingRetryOptions == null) { throw new IllegalArgumentException("retryOptions value must not be null."); } this.throttlingRetryOptions = throttlingRetryOptions; return this; } /** * Gets the flag to enable endpoint discovery for geo-replicated database accounts. * * @return whether endpoint discovery is enabled. */ public boolean isEndpointDiscoveryEnabled() { return this.endpointDiscoveryEnabled; } /** * Sets the flag to enable endpoint discovery for geo-replicated database accounts. * <p> * When EnableEndpointDiscovery is true, the SDK will automatically discover the * current write and read regions to ensure requests are sent to the correct region * based on the capability of the region and the user's preference. * <p> * The default value for this property is true indicating endpoint discovery is enabled. * * @param endpointDiscoveryEnabled true if EndpointDiscovery is enabled. * @return the ConnectionPolicy. */ public ConnectionPolicy setEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) { this.endpointDiscoveryEnabled = endpointDiscoveryEnabled; return this; } /** * Gets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is true indicating that writes are directed to * available writable regions of geo-replicated database account. * * @return flag to enable writes on any regions for geo-replicated database accounts. */ public boolean isMultipleWriteRegionsEnabled() { return this.multipleWriteRegionsEnabled; } /** * Gets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @return flag to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. */ public boolean isReadRequestsFallbackEnabled() { return this.readRequestsFallbackEnabled; } /** * Sets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is false indicating that writes are only directed to * first region in PreferredRegions property. * * @param multipleWriteRegionsEnabled flag to enable writes on any regions for geo-replicated * database accounts. * @return the ConnectionPolicy. */ public ConnectionPolicy setMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) { this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled; return this; } /** * Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @param readRequestsFallbackEnabled flag to enable reads to go to multiple regions configured on an account of * Azure Cosmos DB service. * @return the ConnectionPolicy. */ public ConnectionPolicy setReadRequestsFallbackEnabled(boolean readRequestsFallbackEnabled) { this.readRequestsFallbackEnabled = readRequestsFallbackEnabled; return this; } /** * Gets the preferred regions for geo-replicated database accounts * * @return the list of preferred region. */ public List<String> getPreferredRegions() { return this.preferredRegions != null ? this.preferredRegions : Collections.emptyList(); } /** * Sets the preferred regions for geo-replicated database accounts. For example, * "East US" as the preferred region. * <p> * When EnableEndpointDiscovery is true and PreferredRegions is non-empty, * the SDK will prefer to use the regions in the collection in the order * they are specified to perform operations. * <p> * If EnableEndpointDiscovery is set to false, this property is ignored. * * @param preferredRegions the list of preferred regions. * @return the ConnectionPolicy. */ public ConnectionPolicy setPreferredRegions(List<String> preferredRegions) { this.preferredRegions = preferredRegions; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the ConnectionPolicy. */ public ConnectionPolicy setProxy(ProxyOptions proxy) { this.proxy = proxy; return this; } /** * Gets the direct connect timeout * @return direct connect timeout */ public Duration getConnectTimeout() { return connectTimeout; } /** * Sets the direct connect timeout * @param connectTimeout the connect timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleTcpEndpointTimeout() { return idleTcpEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleTcpEndpointTimeout the idle endpoint timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpEndpointTimeout(Duration idleTcpEndpointTimeout) { this.idleTcpEndpointTimeout = idleTcpEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxConnectionsPerEndpoint the max channels per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per endpoint * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } public boolean isClientTelemetryEnabled() { return clientTelemetryEnabled; } public void setClientTelemetryEnabled(boolean clientTelemetryEnabled) { this.clientTelemetryEnabled = clientTelemetryEnabled; } @Override public String toString() { return "ConnectionPolicy{" + "httpNetworkRequestTimeout=" + httpNetworkRequestTimeout + ", tcpNetworkRequestTimeout=" + tcpNetworkRequestTimeout + ", connectionMode=" + connectionMode + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleHttpConnectionTimeout=" + idleHttpConnectionTimeout + ", idleTcpConnectionTimeout=" + idleTcpConnectionTimeout + ", userAgentSuffix='" + userAgentSuffix + '\'' + ", throttlingRetryOptions=" + throttlingRetryOptions + ", endpointDiscoveryEnabled=" + endpointDiscoveryEnabled + ", preferredRegions=" + preferredRegions + ", multipleWriteRegionsEnabled=" + multipleWriteRegionsEnabled + ", proxyType=" + (proxy != null ? proxy.getType() : null) + ", inetSocketProxyAddress=" + (proxy != null ? proxy.getAddress() : null) + ", readRequestsFallbackEnabled=" + readRequestsFallbackEnabled + ", connectTimeout=" + connectTimeout + ", idleTcpEndpointTimeout=" + idleTcpEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + ", tcpConnectionEndpointRediscoveryEnabled=" + tcpConnectionEndpointRediscoveryEnabled + ", clientTelemetryEnabled=" + clientTelemetryEnabled + '}'; } }
we are not exposing public API in gatewayConnectionConfig, so still need to use BridgeInternal.
public ConnectionPolicy(GatewayConnectionConfig gatewayConnectionConfig) { this(ConnectionMode.GATEWAY); this.idleHttpConnectionTimeout = gatewayConnectionConfig.getIdleConnectionTimeout(); this.maxConnectionPoolSize = gatewayConnectionConfig.getMaxConnectionPoolSize(); this.httpNetworkRequestTimeout = BridgeInternal.getNetworkRequestTimeoutFromGatewayConnectionConfig(gatewayConnectionConfig); this.proxy = gatewayConnectionConfig.getProxy(); this.tcpConnectionEndpointRediscoveryEnabled = false; }
this.httpNetworkRequestTimeout = BridgeInternal.getNetworkRequestTimeoutFromGatewayConnectionConfig(gatewayConnectionConfig);
public ConnectionPolicy(GatewayConnectionConfig gatewayConnectionConfig) { this(ConnectionMode.GATEWAY); this.idleHttpConnectionTimeout = gatewayConnectionConfig.getIdleConnectionTimeout(); this.maxConnectionPoolSize = gatewayConnectionConfig.getMaxConnectionPoolSize(); this.httpNetworkRequestTimeout = BridgeInternal.getNetworkRequestTimeoutFromGatewayConnectionConfig(gatewayConnectionConfig); this.proxy = gatewayConnectionConfig.getProxy(); this.tcpConnectionEndpointRediscoveryEnabled = false; }
class ConnectionPolicy { private static final int defaultGatewayMaxConnectionPoolSize = GatewayConnectionConfig.getDefaultConfig() .getMaxConnectionPoolSize(); private ConnectionMode connectionMode; private boolean endpointDiscoveryEnabled; private boolean multipleWriteRegionsEnabled; private List<String> preferredRegions; private boolean readRequestsFallbackEnabled; private ThrottlingRetryOptions throttlingRetryOptions; private String userAgentSuffix; private int maxConnectionPoolSize; private Duration httpNetworkRequestTimeout; private ProxyOptions proxy; private Duration idleHttpConnectionTimeout; private Duration connectTimeout; private Duration idleTcpConnectionTimeout; private Duration idleTcpEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; private Duration tcpNetworkRequestTimeout; private boolean tcpConnectionEndpointRediscoveryEnabled; private boolean clientTelemetryEnabled; /** * Constructor. */ public ConnectionPolicy(DirectConnectionConfig directConnectionConfig) { this(ConnectionMode.DIRECT); this.connectTimeout = directConnectionConfig.getConnectTimeout(); this.idleTcpConnectionTimeout = directConnectionConfig.getIdleConnectionTimeout(); this.idleTcpEndpointTimeout = directConnectionConfig.getIdleEndpointTimeout(); this.maxConnectionsPerEndpoint = directConnectionConfig.getMaxConnectionsPerEndpoint(); this.maxRequestsPerConnection = directConnectionConfig.getMaxRequestsPerConnection(); this.tcpNetworkRequestTimeout = directConnectionConfig.getNetworkRequestTimeout(); this.tcpConnectionEndpointRediscoveryEnabled = directConnectionConfig.isConnectionEndpointRediscoveryEnabled(); } private ConnectionPolicy(ConnectionMode connectionMode) { this.connectionMode = connectionMode; this.endpointDiscoveryEnabled = true; this.maxConnectionPoolSize = defaultGatewayMaxConnectionPoolSize; this.multipleWriteRegionsEnabled = true; this.readRequestsFallbackEnabled = true; this.throttlingRetryOptions = new ThrottlingRetryOptions(); this.userAgentSuffix = ""; } /** * Gets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return {@code true} if Direct TCP connection endpoint rediscovery should is enabled; {@code false} otherwise. */ public boolean isTcpConnectionEndpointRediscoveryEnabled() { return this.tcpConnectionEndpointRediscoveryEnabled; } /** * Sets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return the {@linkplain ConnectionPolicy}. */ public ConnectionPolicy setTcpConnectionEndpointRediscoveryEnabled(boolean tcpConnectionEndpointRediscoveryEnabled) { this.tcpConnectionEndpointRediscoveryEnabled = tcpConnectionEndpointRediscoveryEnabled; return this; } /** * Gets the default connection policy. * * @return the default connection policy. */ public static ConnectionPolicy getDefaultPolicy() { return new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } /** * Gets the http network request timeout (time to wait for response from network peer). * * @return the http request timeout duration. */ public Duration getHttpNetworkRequestTimeout() { return this.httpNetworkRequestTimeout; } /** * Sets the http network request timeout (time to wait for response from network peer). * The default is 5 seconds. * * @param httpNetworkRequestTimeout the http request timeout duration. * @return the ConnectionPolicy. */ public ConnectionPolicy setHttpNetworkRequestTimeout(Duration httpNetworkRequestTimeout) { this.httpNetworkRequestTimeout = httpNetworkRequestTimeout; return this; } /** * Gets the tcp network request timeout (time to wait for response from network peer). * * @return the request timeout duration. */ public Duration getTcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } /** * Sets the tcp network request timeout (time to wait for response from network peer). * The default is 5 seconds. * * @param tcpNetworkRequestTimeout the request timeout duration. * @return the ConnectionPolicy. */ public ConnectionPolicy setTcpNetworkRequestTimeout(Duration tcpNetworkRequestTimeout) { this.tcpNetworkRequestTimeout = tcpNetworkRequestTimeout; return this; } /** * Gets the connection mode used in the client. * * @return the connection mode. */ public ConnectionMode getConnectionMode() { return this.connectionMode; } /** * Sets the connection mode used in the client. * * @param connectionMode the connection mode. * @return the ConnectionPolicy. */ public ConnectionPolicy setConnectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the ConnectionPolicy. */ public ConnectionPolicy setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle http connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleHttpConnectionTimeout() { return this.idleHttpConnectionTimeout; } /** * sets the value of the timeout for an idle http connection. After that time, * the connection will be automatically closed. * * @param idleHttpConnectionTimeout the duration for an idle connection. * @return the ConnectionPolicy. */ public ConnectionPolicy setIdleHttpConnectionTimeout(Duration idleHttpConnectionTimeout) { this.idleHttpConnectionTimeout = idleHttpConnectionTimeout; return this; } /** * Gets the idle tcp connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle tcp connection timeout */ public Duration getIdleTcpConnectionTimeout() { return idleTcpConnectionTimeout; } /** * Sets the idle tcp connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleTcpConnectionTimeout idle connection timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpConnectionTimeout(Duration idleTcpConnectionTimeout) { this.idleTcpConnectionTimeout = idleTcpConnectionTimeout; return this; } /** * Gets the value of user-agent suffix. * * @return the value of user-agent suffix. */ public String getUserAgentSuffix() { return this.userAgentSuffix; } /** * sets the value of the user-agent suffix. * * @param userAgentSuffix The value to be appended to the user-agent header, this is * used for monitoring purposes. * @return the ConnectionPolicy. */ public ConnectionPolicy setUserAgentSuffix(String userAgentSuffix) { this.userAgentSuffix = userAgentSuffix; return this; } /** * Gets the retry policy options associated with the DocumentClient instance. * * @return the RetryOptions instance. */ public ThrottlingRetryOptions getThrottlingRetryOptions() { return this.throttlingRetryOptions; } /** * Sets the retry policy options associated with the DocumentClient instance. * <p> * Properties in the RetryOptions class allow application to customize the built-in * retry policies. This property is optional. When it's not set, the SDK uses the * default values for configuring the retry policies. See RetryOptions class for * more details. * * @param throttlingRetryOptions the RetryOptions instance. * @return the ConnectionPolicy. * @throws IllegalArgumentException thrown if an error occurs */ public ConnectionPolicy setThrottlingRetryOptions(ThrottlingRetryOptions throttlingRetryOptions) { if (throttlingRetryOptions == null) { throw new IllegalArgumentException("retryOptions value must not be null."); } this.throttlingRetryOptions = throttlingRetryOptions; return this; } /** * Gets the flag to enable endpoint discovery for geo-replicated database accounts. * * @return whether endpoint discovery is enabled. */ public boolean isEndpointDiscoveryEnabled() { return this.endpointDiscoveryEnabled; } /** * Sets the flag to enable endpoint discovery for geo-replicated database accounts. * <p> * When EnableEndpointDiscovery is true, the SDK will automatically discover the * current write and read regions to ensure requests are sent to the correct region * based on the capability of the region and the user's preference. * <p> * The default value for this property is true indicating endpoint discovery is enabled. * * @param endpointDiscoveryEnabled true if EndpointDiscovery is enabled. * @return the ConnectionPolicy. */ public ConnectionPolicy setEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) { this.endpointDiscoveryEnabled = endpointDiscoveryEnabled; return this; } /** * Gets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is true indicating that writes are directed to * available writable regions of geo-replicated database account. * * @return flag to enable writes on any regions for geo-replicated database accounts. */ public boolean isMultipleWriteRegionsEnabled() { return this.multipleWriteRegionsEnabled; } /** * Gets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @return flag to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. */ public boolean isReadRequestsFallbackEnabled() { return this.readRequestsFallbackEnabled; } /** * Sets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is false indicating that writes are only directed to * first region in PreferredRegions property. * * @param multipleWriteRegionsEnabled flag to enable writes on any regions for geo-replicated * database accounts. * @return the ConnectionPolicy. */ public ConnectionPolicy setMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) { this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled; return this; } /** * Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @param readRequestsFallbackEnabled flag to enable reads to go to multiple regions configured on an account of * Azure Cosmos DB service. * @return the ConnectionPolicy. */ public ConnectionPolicy setReadRequestsFallbackEnabled(boolean readRequestsFallbackEnabled) { this.readRequestsFallbackEnabled = readRequestsFallbackEnabled; return this; } /** * Gets the preferred regions for geo-replicated database accounts * * @return the list of preferred region. */ public List<String> getPreferredRegions() { return this.preferredRegions != null ? this.preferredRegions : Collections.emptyList(); } /** * Sets the preferred regions for geo-replicated database accounts. For example, * "East US" as the preferred region. * <p> * When EnableEndpointDiscovery is true and PreferredRegions is non-empty, * the SDK will prefer to use the regions in the collection in the order * they are specified to perform operations. * <p> * If EnableEndpointDiscovery is set to false, this property is ignored. * * @param preferredRegions the list of preferred regions. * @return the ConnectionPolicy. */ public ConnectionPolicy setPreferredRegions(List<String> preferredRegions) { this.preferredRegions = preferredRegions; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the ConnectionPolicy. */ public ConnectionPolicy setProxy(ProxyOptions proxy) { this.proxy = proxy; return this; } /** * Gets the direct connect timeout * @return direct connect timeout */ public Duration getConnectTimeout() { return connectTimeout; } /** * Sets the direct connect timeout * @param connectTimeout the connect timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleTcpEndpointTimeout() { return idleTcpEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleTcpEndpointTimeout the idle endpoint timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpEndpointTimeout(Duration idleTcpEndpointTimeout) { this.idleTcpEndpointTimeout = idleTcpEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxConnectionsPerEndpoint the max channels per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per endpoint * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } public boolean isClientTelemetryEnabled() { return clientTelemetryEnabled; } public void setClientTelemetryEnabled(boolean clientTelemetryEnabled) { this.clientTelemetryEnabled = clientTelemetryEnabled; } @Override public String toString() { return "ConnectionPolicy{" + "httpNetworkRequestTimeout=" + httpNetworkRequestTimeout + ", tcpNetworkRequestTimeout=" + tcpNetworkRequestTimeout + ", connectionMode=" + connectionMode + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleHttpConnectionTimeout=" + idleHttpConnectionTimeout + ", idleTcpConnectionTimeout=" + idleTcpConnectionTimeout + ", userAgentSuffix='" + userAgentSuffix + '\'' + ", throttlingRetryOptions=" + throttlingRetryOptions + ", endpointDiscoveryEnabled=" + endpointDiscoveryEnabled + ", preferredRegions=" + preferredRegions + ", multipleWriteRegionsEnabled=" + multipleWriteRegionsEnabled + ", proxyType=" + (proxy != null ? proxy.getType() : null) + ", inetSocketProxyAddress=" + (proxy != null ? proxy.getAddress() : null) + ", readRequestsFallbackEnabled=" + readRequestsFallbackEnabled + ", connectTimeout=" + connectTimeout + ", idleTcpEndpointTimeout=" + idleTcpEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + ", tcpConnectionEndpointRediscoveryEnabled=" + tcpConnectionEndpointRediscoveryEnabled + ", clientTelemetryEnabled=" + clientTelemetryEnabled + '}'; } }
class ConnectionPolicy { private static final int defaultGatewayMaxConnectionPoolSize = GatewayConnectionConfig.getDefaultConfig() .getMaxConnectionPoolSize(); private ConnectionMode connectionMode; private boolean endpointDiscoveryEnabled; private boolean multipleWriteRegionsEnabled; private List<String> preferredRegions; private boolean readRequestsFallbackEnabled; private ThrottlingRetryOptions throttlingRetryOptions; private String userAgentSuffix; private int maxConnectionPoolSize; private Duration httpNetworkRequestTimeout; private ProxyOptions proxy; private Duration idleHttpConnectionTimeout; private Duration connectTimeout; private Duration idleTcpConnectionTimeout; private Duration idleTcpEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; private Duration tcpNetworkRequestTimeout; private boolean tcpConnectionEndpointRediscoveryEnabled; private boolean clientTelemetryEnabled; /** * Constructor. */ public ConnectionPolicy(DirectConnectionConfig directConnectionConfig) { this(ConnectionMode.DIRECT); this.connectTimeout = directConnectionConfig.getConnectTimeout(); this.idleTcpConnectionTimeout = directConnectionConfig.getIdleConnectionTimeout(); this.idleTcpEndpointTimeout = directConnectionConfig.getIdleEndpointTimeout(); this.maxConnectionsPerEndpoint = directConnectionConfig.getMaxConnectionsPerEndpoint(); this.maxRequestsPerConnection = directConnectionConfig.getMaxRequestsPerConnection(); this.tcpNetworkRequestTimeout = directConnectionConfig.getNetworkRequestTimeout(); this.tcpConnectionEndpointRediscoveryEnabled = directConnectionConfig.isConnectionEndpointRediscoveryEnabled(); } private ConnectionPolicy(ConnectionMode connectionMode) { this.connectionMode = connectionMode; this.endpointDiscoveryEnabled = true; this.maxConnectionPoolSize = defaultGatewayMaxConnectionPoolSize; this.multipleWriteRegionsEnabled = true; this.readRequestsFallbackEnabled = true; this.throttlingRetryOptions = new ThrottlingRetryOptions(); this.userAgentSuffix = ""; } /** * Gets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return {@code true} if Direct TCP connection endpoint rediscovery should is enabled; {@code false} otherwise. */ public boolean isTcpConnectionEndpointRediscoveryEnabled() { return this.tcpConnectionEndpointRediscoveryEnabled; } /** * Sets a value that indicates whether Direct TCP connection endpoint rediscovery is enabled. * * @return the {@linkplain ConnectionPolicy}. */ public ConnectionPolicy setTcpConnectionEndpointRediscoveryEnabled(boolean tcpConnectionEndpointRediscoveryEnabled) { this.tcpConnectionEndpointRediscoveryEnabled = tcpConnectionEndpointRediscoveryEnabled; return this; } /** * Gets the default connection policy. * * @return the default connection policy. */ public static ConnectionPolicy getDefaultPolicy() { return new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } /** * Gets the http network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @return the http request timeout duration. */ public Duration getHttpNetworkRequestTimeout() { return this.httpNetworkRequestTimeout; } /** * Sets the http network request timeout interval (time to wait for response from network peer). * The default is 60 seconds. * * @param httpNetworkRequestTimeout the http request timeout duration. * @return the ConnectionPolicy. */ public ConnectionPolicy setHttpNetworkRequestTimeout(Duration httpNetworkRequestTimeout) { this.httpNetworkRequestTimeout = httpNetworkRequestTimeout; return this; } /** * Gets the tcp network request timeout interval (time to wait for response from network peer). * * Default value is 5 seconds * * @return the network request timeout interval */ public Duration getTcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } /** * Sets the tcp network request timeout interval (time to wait for response from network peer). * * Default value is 5 seconds. * It only allows values &ge;5s and &le;10s. (backend allows requests to take up-to 5 seconds processing time - 5 seconds * buffer so 10 seconds in total for transport is more than sufficient). * * Attention! Please adjust this value with caution. * This config represents the max time allowed to wait for and consume a service response after the request has been written to the network connection. * Setting a value too low can result in having not enough time to wait for the service response - which could cause too aggressive retries and degrade performance. * Setting a value too high can result in fewer retries and reduce chances of success by retries. * * @param tcpNetworkRequestTimeout the network request timeout interval. * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setTcpNetworkRequestTimeout(Duration tcpNetworkRequestTimeout) { this.tcpNetworkRequestTimeout = tcpNetworkRequestTimeout; return this; } /** * Gets the connection mode used in the client. * * @return the connection mode. */ public ConnectionMode getConnectionMode() { return this.connectionMode; } /** * Sets the connection mode used in the client. * * @param connectionMode the connection mode. * @return the ConnectionPolicy. */ public ConnectionPolicy setConnectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the ConnectionPolicy. */ public ConnectionPolicy setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle http connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleHttpConnectionTimeout() { return this.idleHttpConnectionTimeout; } /** * sets the value of the timeout for an idle http connection. After that time, * the connection will be automatically closed. * * @param idleHttpConnectionTimeout the duration for an idle connection. * @return the ConnectionPolicy. */ public ConnectionPolicy setIdleHttpConnectionTimeout(Duration idleHttpConnectionTimeout) { this.idleHttpConnectionTimeout = idleHttpConnectionTimeout; return this; } /** * Gets the idle tcp connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle tcp connection timeout */ public Duration getIdleTcpConnectionTimeout() { return idleTcpConnectionTimeout; } /** * Sets the idle tcp connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleTcpConnectionTimeout idle connection timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpConnectionTimeout(Duration idleTcpConnectionTimeout) { this.idleTcpConnectionTimeout = idleTcpConnectionTimeout; return this; } /** * Gets the value of user-agent suffix. * * @return the value of user-agent suffix. */ public String getUserAgentSuffix() { return this.userAgentSuffix; } /** * sets the value of the user-agent suffix. * * @param userAgentSuffix The value to be appended to the user-agent header, this is * used for monitoring purposes. * @return the ConnectionPolicy. */ public ConnectionPolicy setUserAgentSuffix(String userAgentSuffix) { this.userAgentSuffix = userAgentSuffix; return this; } /** * Gets the retry policy options associated with the DocumentClient instance. * * @return the RetryOptions instance. */ public ThrottlingRetryOptions getThrottlingRetryOptions() { return this.throttlingRetryOptions; } /** * Sets the retry policy options associated with the DocumentClient instance. * <p> * Properties in the RetryOptions class allow application to customize the built-in * retry policies. This property is optional. When it's not set, the SDK uses the * default values for configuring the retry policies. See RetryOptions class for * more details. * * @param throttlingRetryOptions the RetryOptions instance. * @return the ConnectionPolicy. * @throws IllegalArgumentException thrown if an error occurs */ public ConnectionPolicy setThrottlingRetryOptions(ThrottlingRetryOptions throttlingRetryOptions) { if (throttlingRetryOptions == null) { throw new IllegalArgumentException("retryOptions value must not be null."); } this.throttlingRetryOptions = throttlingRetryOptions; return this; } /** * Gets the flag to enable endpoint discovery for geo-replicated database accounts. * * @return whether endpoint discovery is enabled. */ public boolean isEndpointDiscoveryEnabled() { return this.endpointDiscoveryEnabled; } /** * Sets the flag to enable endpoint discovery for geo-replicated database accounts. * <p> * When EnableEndpointDiscovery is true, the SDK will automatically discover the * current write and read regions to ensure requests are sent to the correct region * based on the capability of the region and the user's preference. * <p> * The default value for this property is true indicating endpoint discovery is enabled. * * @param endpointDiscoveryEnabled true if EndpointDiscovery is enabled. * @return the ConnectionPolicy. */ public ConnectionPolicy setEndpointDiscoveryEnabled(boolean endpointDiscoveryEnabled) { this.endpointDiscoveryEnabled = endpointDiscoveryEnabled; return this; } /** * Gets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is true indicating that writes are directed to * available writable regions of geo-replicated database account. * * @return flag to enable writes on any regions for geo-replicated database accounts. */ public boolean isMultipleWriteRegionsEnabled() { return this.multipleWriteRegionsEnabled; } /** * Gets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @return flag to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. */ public boolean isReadRequestsFallbackEnabled() { return this.readRequestsFallbackEnabled; } /** * Sets the flag to enable writes on any regions for geo-replicated database accounts in the Azure * Cosmos DB service. * <p> * When the value of this property is true, the SDK will direct write operations to * available writable regions of geo-replicated database account. Writable regions * are ordered by PreferredRegions property. Setting the property value * to true has no effect until EnableMultipleWriteRegions in DatabaseAccount * is also set to true. * <p> * DEFAULT value is false indicating that writes are only directed to * first region in PreferredRegions property. * * @param multipleWriteRegionsEnabled flag to enable writes on any regions for geo-replicated * database accounts. * @return the ConnectionPolicy. */ public ConnectionPolicy setMultipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled) { this.multipleWriteRegionsEnabled = multipleWriteRegionsEnabled; return this; } /** * Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * <p> * DEFAULT value is true. * <p> * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. * 1. {@link * 2. the Azure Cosmos DB account has more than one region * * @param readRequestsFallbackEnabled flag to enable reads to go to multiple regions configured on an account of * Azure Cosmos DB service. * @return the ConnectionPolicy. */ public ConnectionPolicy setReadRequestsFallbackEnabled(boolean readRequestsFallbackEnabled) { this.readRequestsFallbackEnabled = readRequestsFallbackEnabled; return this; } /** * Gets the preferred regions for geo-replicated database accounts * * @return the list of preferred region. */ public List<String> getPreferredRegions() { return this.preferredRegions != null ? this.preferredRegions : Collections.emptyList(); } /** * Sets the preferred regions for geo-replicated database accounts. For example, * "East US" as the preferred region. * <p> * When EnableEndpointDiscovery is true and PreferredRegions is non-empty, * the SDK will prefer to use the regions in the collection in the order * they are specified to perform operations. * <p> * If EnableEndpointDiscovery is set to false, this property is ignored. * * @param preferredRegions the list of preferred regions. * @return the ConnectionPolicy. */ public ConnectionPolicy setPreferredRegions(List<String> preferredRegions) { this.preferredRegions = preferredRegions; return this; } /** * Gets the proxy options which contain the InetSocketAddress of proxy server. * * @return the proxy options. */ public ProxyOptions getProxy() { return this.proxy; } /** * Sets the proxy options. * * Currently only support Http proxy type with just the routing address. Username and password will be ignored. * * @param proxy The proxy options. * @return the ConnectionPolicy. */ public ConnectionPolicy setProxy(ProxyOptions proxy) { this.proxy = proxy; return this; } /** * Gets the direct connect timeout * @return direct connect timeout */ public Duration getConnectTimeout() { return connectTimeout; } /** * Sets the direct connect timeout * @param connectTimeout the connect timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleTcpEndpointTimeout() { return idleTcpEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleTcpEndpointTimeout the idle endpoint timeout * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setIdleTcpEndpointTimeout(Duration idleTcpEndpointTimeout) { this.idleTcpEndpointTimeout = idleTcpEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxConnectionsPerEndpoint the max channels per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per endpoint * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link ConnectionPolicy} */ public ConnectionPolicy setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } public boolean isClientTelemetryEnabled() { return clientTelemetryEnabled; } public void setClientTelemetryEnabled(boolean clientTelemetryEnabled) { this.clientTelemetryEnabled = clientTelemetryEnabled; } @Override public String toString() { return "ConnectionPolicy{" + "httpNetworkRequestTimeout=" + httpNetworkRequestTimeout + ", tcpNetworkRequestTimeout=" + tcpNetworkRequestTimeout + ", connectionMode=" + connectionMode + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleHttpConnectionTimeout=" + idleHttpConnectionTimeout + ", idleTcpConnectionTimeout=" + idleTcpConnectionTimeout + ", userAgentSuffix='" + userAgentSuffix + '\'' + ", throttlingRetryOptions=" + throttlingRetryOptions + ", endpointDiscoveryEnabled=" + endpointDiscoveryEnabled + ", preferredRegions=" + preferredRegions + ", multipleWriteRegionsEnabled=" + multipleWriteRegionsEnabled + ", proxyType=" + (proxy != null ? proxy.getType() : null) + ", inetSocketProxyAddress=" + (proxy != null ? proxy.getAddress() : null) + ", readRequestsFallbackEnabled=" + readRequestsFallbackEnabled + ", connectTimeout=" + connectTimeout + ", idleTcpEndpointTimeout=" + idleTcpEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + ", tcpConnectionEndpointRediscoveryEnabled=" + tcpConnectionEndpointRediscoveryEnabled + ", clientTelemetryEnabled=" + clientTelemetryEnabled + '}'; } }
extra colon, also in a few other places ```suggestion // see https://aka.ms/azsdk/textanalytics/customfunctionalities ```
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = new ArrayList<>(); documents.add( "I need a reservation for an indoor restaurant in China. Please don't stop the music." + " Play music and add it to my playlist" ); SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> syncPoller = client.beginAnalyzeActions(documents, new TextAnalyticsActions().setMultiCategoryClassifyActions( new MultiCategoryClassifyAction("{project_name}", "{deployment_name}")), "en", null); syncPoller.waitForCompletion(); syncPoller.getFinalResult().forEach(actionsResult -> { for (MultiCategoryClassifyActionResult actionResult : actionsResult.getMultiCategoryClassifyResults()) { if (!actionResult.isError()) { final MultiCategoryClassifyResultCollection documentsResults = actionResult.getDocumentsResults(); System.out.printf("Project name: %s, deployment name: %s.%n", documentsResults.getProjectName(), documentsResults.getDeploymentName()); for (MultiCategoryClassifyResult documentResult : documentsResults) { System.out.println("Document ID: " + documentResult.getId()); if (!documentResult.isError()) { for (ClassificationCategory classificationCategory : documentResult.getClassifications()) { System.out.printf("\tCategory: %s, confidence score: %f.%n", classificationCategory.getCategory(), classificationCategory.getConfidenceScore()); } } else { System.out.printf("\tCannot classify multi categories of document. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute 'MultiCategoryClassifyAction'. Error: %s%n", actionResult.getError().getMessage()); } } }); }
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = new ArrayList<>(); documents.add( "I need a reservation for an indoor restaurant in China. Please don't stop the music." + " Play music and add it to my playlist" ); SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> syncPoller = client.beginAnalyzeActions(documents, new TextAnalyticsActions().setMultiCategoryClassifyActions( new MultiCategoryClassifyAction("{project_name}", "{deployment_name}")), "en", null); syncPoller.waitForCompletion(); syncPoller.getFinalResult().forEach(actionsResult -> { for (MultiCategoryClassifyActionResult actionResult : actionsResult.getMultiCategoryClassifyResults()) { if (!actionResult.isError()) { final MultiCategoryClassifyResultCollection documentsResults = actionResult.getDocumentsResults(); System.out.printf("Project name: %s, deployment name: %s.%n", documentsResults.getProjectName(), documentsResults.getDeploymentName()); for (MultiCategoryClassifyResult documentResult : documentsResults) { System.out.println("Document ID: " + documentResult.getId()); if (!documentResult.isError()) { for (ClassificationCategory classificationCategory : documentResult.getClassifications()) { System.out.printf("\tCategory: %s, confidence score: %f.%n", classificationCategory.getCategory(), classificationCategory.getConfidenceScore()); } } else { System.out.printf("\tCannot classify multi categories of document. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute 'MultiCategoryClassifyAction'. Error: %s%n", actionResult.getError().getMessage()); } } }); }
class ClassifyDocumentMultiCategory { /** * Main method to invoke this demo about how to analyze an "Multi-label Classification" action. * * @param args Unused arguments to the program. */ }
class ClassifyDocumentMultiCategory { /** * Main method to invoke this demo about how to analyze an "Multi-label Classification" action. * * @param args Unused arguments to the program. */ }
Is there a reason we're updating this test that should test AzureNamedKeyCredential to EventHubSharedKeyCredential?
public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessKeyName, sharedAccessKey, ClientConstants.TOKEN_VALIDITY)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
new EventHubSharedKeyCredential(sharedAccessKeyName,
public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test @Test public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test @Test public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureSasCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } }
This test case is to test a SasCredential.
public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
new EventHubSharedKeyCredential(sharedAccessSignature))
public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureSasCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessKeyName, sharedAccessKey, ClientConstants.TOKEN_VALIDITY)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } @Test }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } @Test }
The intention of this test was that we would receive from all 6 partitions. The test here is updated so that it receives 6 times, it doesn't discern between what partitions were received from.
public void receivesMultiplePartitions() { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block(TIMEOUT)))); final Set<Integer> expectedPartitions = new HashSet<>(allPartitions); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() <= expectedNumber, "Cannot run this test if there are more partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); AtomicInteger removedPartitionsNumber = new AtomicInteger(expectedNumber); try { StepVerifier.create(consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber)) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } Assertions.assertTrue(removedPartitionsNumber.get() == 0, "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); }
.take(expectedNumber))
public void receivesMultiplePartitions() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final Set<Integer> expectedPartitions = Collections.synchronizedSet(new HashSet<>(allPartitions)); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .map(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); return event; }) .repeat(() -> expectedPartitions.size() > 0) .collectList() .block(); }); thread.start(); thread.join(TIMEOUT.toMillis()); Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); Assertions.assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); Assertions.assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { Assertions.assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } Assertions.assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { Assertions.assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); Assertions.assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); Assertions.assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); Assertions.assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); Assertions.assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); Assertions.assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
Since this test case sets a limit on the number of received pieces, in order to eliminate the interference of other test case data on the verification results, so modified the filter conditions of the receive event data.
public void receivesMultiplePartitions() { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block(TIMEOUT)))); final Set<Integer> expectedPartitions = new HashSet<>(allPartitions); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() <= expectedNumber, "Cannot run this test if there are more partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); AtomicInteger removedPartitionsNumber = new AtomicInteger(expectedNumber); try { StepVerifier.create(consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber)) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } Assertions.assertTrue(removedPartitionsNumber.get() == 0, "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); }
.take(expectedNumber))
public void receivesMultiplePartitions() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final Set<Integer> expectedPartitions = Collections.synchronizedSet(new HashSet<>(allPartitions)); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .map(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); return event; }) .repeat(() -> expectedPartitions.size() > 0) .collectList() .block(); }); thread.start(); thread.join(TIMEOUT.toMillis()); Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); Assertions.assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); Assertions.assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { Assertions.assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } Assertions.assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { Assertions.assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); Assertions.assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); Assertions.assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); Assertions.assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); Assertions.assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); Assertions.assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
The code has been rollback to the original settings and successfully passed the test on UsGov and China cloud by pipeline.
public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
new EventHubSharedKeyCredential(sharedAccessSignature))
public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureSasCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessKeyName, sharedAccessKey, ClientConstants.TOKEN_VALIDITY)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } @Test }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } @Test }
The code has been rollback to the original settings and successfully passed the test on UsGov and China cloud by pipeline.
public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessKeyName, sharedAccessKey, ClientConstants.TOKEN_VALIDITY)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
new EventHubSharedKeyCredential(sharedAccessKeyName,
public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessKeyName = properties.getSharedAccessKeyName(); String sharedAccessKey = properties.getSharedAccessKey(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureNamedKeyCredential(sharedAccessKeyName, sharedAccessKey)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test @Test public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new EventHubSharedKeyCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } }
class EventHubAsyncClientIntegrationTest extends IntegrationTestBase { private static final int NUMBER_OF_EVENTS = 5; private static final String PARTITION_ID = "1"; private IntegrationTestEventData testEventData; private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \nUt sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \nAenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \nAenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \nDonec quis ipsum ultricies, imperdiet ex vel, scelerisque eros. Ut at urna arcu. Vestibulum rutrum odio dolor, vitae cursus nunc pulvinar vel. Donec accumsan sapien in malesuada tempor. Maecenas in condimentum eros. Sed vestibulum facilisis massa a iaculis. Etiam et nibh felis. Donec maximus, sem quis vestibulum gravida, turpis risus congue dolor, pharetra tincidunt lectus nisi at velit."; EventHubAsyncClientIntegrationTest() { super(new ClientLogger(EventHubAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { final Map<String, IntegrationTestEventData> testData = getTestData(); testEventData = testData.get(PARTITION_ID); Assertions.assertNotNull(testEventData, PARTITION_ID + " should have been able to get data for partition."); } /** * Verifies that we can receive messages, and that the receiver continues to fetch messages when the prefetch queue * is exhausted. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void receiveMessage(AmqpTransportType transportType) { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .transportType(transportType) .buildAsyncConsumerClient(); final Instant lastEnqueued = testEventData.getPartitionProperties().getLastEnqueuedTime(); final EventPosition startingPosition = EventPosition.fromEnqueuedTime(lastEnqueued); try { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, startingPosition) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) .expectComplete() .verify(); } finally { consumer.close(); } } /** * Verifies that we can have multiple consumers listening to the same partition + consumer group at the same time. */ @ParameterizedTest @EnumSource(value = AmqpTransportType.class) void parallelEventHubClients(AmqpTransportType transportType) throws InterruptedException { final int numberOfClients = 3; final int numberOfEvents = testEventData.getEvents().size() - 2; final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); final EventHubClientBuilder builder = createBuilder() .transportType(transportType) .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME); final EventHubConsumerAsyncClient[] clients = new EventHubConsumerAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { clients[i] = builder.buildAsyncConsumerClient(); } final long sequenceNumber = testEventData.getPartitionProperties().getLastEnqueuedSequenceNumber(); final EventPosition position = EventPosition.fromSequenceNumber(sequenceNumber); try { for (final EventHubConsumerAsyncClient consumer : clients) { consumer.receiveFromPartition(PARTITION_ID, position) .filter(partitionEvent -> isMatchingEvent(partitionEvent.getData(), testEventData.getMessageId())) .take(numberOfEvents) .subscribe(partitionEvent -> { EventData event = partitionEvent.getData(); logger.info("Event[{}] matched.", event.getSequenceNumber()); }, error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { long count = countDownLatch.getCount(); logger.info("Finished consuming events. Counting down: {}", count); countDownLatch.countDown(); }); } Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); logger.info("Completed successfully."); } finally { logger.info("Disposing of subscriptions, consumers and clients."); dispose(clients); } } /** * Sending with credentials. */ @Test void getPropertiesWithCredentials() { try (EventHubAsyncClient client = createBuilder(true) .buildAsyncClient()) { StepVerifier.create(client.getProperties()) .assertNext(properties -> { Assertions.assertEquals(getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }) .expectComplete() .verify(TIMEOUT); } } @Test @Test public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); ConnectionStringProperties properties = getConnectionStringProperties(true); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); String sharedAccessSignature = properties.getSharedAccessSignature(); String eventHubName = properties.getEntityPath(); final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); EventHubProducerAsyncClient asyncProducerClient = new EventHubClientBuilder() .credential(fullyQualifiedNamespace, eventHubName, new AzureSasCredential(sharedAccessSignature)) .buildAsyncProducerClient(); try { StepVerifier.create( asyncProducerClient.createBatch().flatMap(batch -> { assertTrue(batch.tryAdd(testData)); return asyncProducerClient.send(batch); }) ).verifyComplete(); } finally { asyncProducerClient.close(); } } }
@conniey Any ideas?
public void receivesMultiplePartitions() { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block(TIMEOUT)))); final Set<Integer> expectedPartitions = new HashSet<>(allPartitions); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() <= expectedNumber, "Cannot run this test if there are more partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); AtomicInteger removedPartitionsNumber = new AtomicInteger(expectedNumber); try { StepVerifier.create(consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber)) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .assertNext(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); removedPartitionsNumber.decrementAndGet(); }) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } Assertions.assertTrue(removedPartitionsNumber.get() == 0, "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); }
.take(expectedNumber))
public void receivesMultiplePartitions() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final Set<Integer> expectedPartitions = Collections.synchronizedSet(new HashSet<>(allPartitions)); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .map(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); return event; }) .repeat(() -> expectedPartitions.size() > 0) .collectList() .block(); }); thread.start(); thread.join(TIMEOUT.toMillis()); Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); Assertions.assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); Assertions.assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { Assertions.assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } Assertions.assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { Assertions.assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); Assertions.assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); Assertions.assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); Assertions.assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); Assertions.assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); Assertions.assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
If we can't join is printing a stack trace enough? Does that mean the test still passes? Or that it fails? You can have the method throw an InterruptedException if you don't want to explicitly add an assertFail
public void receivesMultiplePartitions() { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final List<PartitionEvent> partitionEvents = Collections.synchronizedList(new ArrayList<PartitionEvent>()); final Set<Integer> expectedPartitions = new HashSet<>(allPartitions); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); event.getProperties().put(TestUtils.MESSAGE_ID, MESSAGE_TRACKING_ID); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { partitionEvents.addAll(consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .collectList().block()); }); thread.start(); thread.join(TIMEOUT.toMillis()); assertEquals(expectedNumber, partitionEvents.size()); partitionEvents.stream().forEach(event -> assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions)); } catch (InterruptedException e) { e.printStackTrace(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); }
e.printStackTrace();
public void receivesMultiplePartitions() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final Set<Integer> expectedPartitions = Collections.synchronizedSet(new HashSet<>(allPartitions)); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .map(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); return event; }) .repeat(() -> expectedPartitions.size() > 0) .collectList() .block(); }); thread.start(); thread.join(TIMEOUT.toMillis()); Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { assertNotNull(properties); assertEquals(consumer.getEventHubName(), properties.getName()); assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { assertEquals(consumer.getEventHubName(), properties.getEventHubName()); assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); assertNotNull(events); assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); Assertions.assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); Assertions.assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { Assertions.assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } Assertions.assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { Assertions.assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); Assertions.assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); Assertions.assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); Assertions.assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); Assertions.assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); Assertions.assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
I noticed some other test cases, the method throws InterruptedException, to be consistent, we might want to do the same.
public void receivesMultiplePartitions() { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final List<PartitionEvent> partitionEvents = Collections.synchronizedList(new ArrayList<PartitionEvent>()); final Set<Integer> expectedPartitions = new HashSet<>(allPartitions); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); event.getProperties().put(TestUtils.MESSAGE_ID, MESSAGE_TRACKING_ID); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { partitionEvents.addAll(consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .collectList().block()); }); thread.start(); thread.join(TIMEOUT.toMillis()); assertEquals(expectedNumber, partitionEvents.size()); partitionEvents.stream().forEach(event -> assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions)); } catch (InterruptedException e) { e.printStackTrace(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); }
e.printStackTrace();
public void receivesMultiplePartitions() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final Set<Integer> expectedPartitions = Collections.synchronizedSet(new HashSet<>(allPartitions)); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .map(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); return event; }) .repeat(() -> expectedPartitions.size() > 0) .collectList() .block(); }); thread.start(); thread.join(TIMEOUT.toMillis()); Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { assertNotNull(properties); assertEquals(consumer.getEventHubName(), properties.getName()); assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { assertEquals(consumer.getEventHubName(), properties.getEventHubName()); assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); assertNotNull(events); assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); Assertions.assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); Assertions.assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { Assertions.assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } Assertions.assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { Assertions.assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); Assertions.assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); Assertions.assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); Assertions.assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); Assertions.assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); Assertions.assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
According to your comment, fixed in the new version.
public void receivesMultiplePartitions() { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final List<PartitionEvent> partitionEvents = Collections.synchronizedList(new ArrayList<PartitionEvent>()); final Set<Integer> expectedPartitions = new HashSet<>(allPartitions); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); event.getProperties().put(TestUtils.MESSAGE_ID, MESSAGE_TRACKING_ID); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { partitionEvents.addAll(consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .collectList().block()); }); thread.start(); thread.join(TIMEOUT.toMillis()); assertEquals(expectedNumber, partitionEvents.size()); partitionEvents.stream().forEach(event -> assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions)); } catch (InterruptedException e) { e.printStackTrace(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); }
e.printStackTrace();
public void receivesMultiplePartitions() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final AtomicInteger counter = new AtomicInteger(); final Set<Integer> allPartitions = Collections.unmodifiableSet(new HashSet<>(Objects.requireNonNull( consumer.getPartitionIds().map(Integer::valueOf).collectList().block()))); final Set<Integer> expectedPartitions = Collections.synchronizedSet(new HashSet<>(allPartitions)); final int expectedNumber = 6; Assumptions.assumeTrue(expectedPartitions.size() < expectedNumber, "Cannot run this test if there are less partitions than expected."); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { final int partition = counter.getAndIncrement() % allPartitions.size(); event.getProperties().put(PARTITION_ID_HEADER, partition); return producer.send(event, new SendOptions().setPartitionId(String.valueOf(partition))); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); try { Thread thread = new Thread(() -> { consumer.receive(false) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(expectedNumber) .map(event -> { assertPartitionEvent(event, producer.getEventHubName(), allPartitions, expectedPartitions); return event; }) .repeat(() -> expectedPartitions.size() > 0) .collectList() .block(); }); thread.start(); thread.join(TIMEOUT.toMillis()); Assertions.assertTrue(expectedPartitions.isEmpty(), "Expected messages to be received from all partitions. " + "There are: " + expectedPartitions.size()); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { assertNotNull(properties); assertEquals(consumer.getEventHubName(), properties.getName()); assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { assertEquals(consumer.getEventHubName(), properties.getEventHubName()); assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); assertNotNull(events); assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
class EventHubConsumerAsyncClientIntegrationTest extends IntegrationTestBase { private static final String PARTITION_ID_HEADER = "SENT_PARTITION_ID"; private static final String MESSAGE_TRACKING_ID = UUID.randomUUID().toString(); private EventHubClientBuilder builder; private List<String> partitionIds; public EventHubConsumerAsyncClientIntegrationTest() { super(new ClientLogger(EventHubConsumerAsyncClientIntegrationTest.class)); } @Override protected void beforeTest() { builder = createBuilder() .shareConnection() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .prefetchCount(DEFAULT_PREFETCH_COUNT); partitionIds = EXPECTED_PARTITION_IDS; } /** * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { final Map<String, IntegrationTestEventData> testData = getTestData(); final CountDownLatch countDownLatch = new CountDownLatch(partitionIds.size()); final EventHubConsumerAsyncClient[] consumers = new EventHubConsumerAsyncClient[partitionIds.size()]; final Disposable.Composite subscriptions = Disposables.composite(); try { for (int i = 0; i < partitionIds.size(); i++) { final String partitionId = partitionIds.get(i); final IntegrationTestEventData matchingTestData = testData.get(partitionId); Assertions.assertNotNull(matchingTestData, "Did not find matching integration test data for partition: " + partitionId); final Instant lastEnqueuedTime = matchingTestData.getPartitionProperties().getLastEnqueuedTime(); final EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient(); consumers[i] = consumer; final Disposable subscription = consumer.receiveFromPartition(partitionId, EventPosition.fromEnqueuedTime(lastEnqueuedTime)) .take(matchingTestData.getEvents().size()) .subscribe( event -> logger.info("Event[{}] received. partition: {}", event.getData().getSequenceNumber(), partitionId), error -> Assertions.fail("An error should not have occurred:" + error.toString()), () -> { logger.info("Disposing of consumer now that the receive is complete."); countDownLatch.countDown(); }); subscriptions.add(subscription); } countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertEquals(0, countDownLatch.getCount()); } catch (InterruptedException e) { Assertions.fail("Countdown latch was interrupted:" + e); } finally { logger.info("Disposing of subscriptions, consumers, producers."); subscriptions.dispose(); dispose(consumers); } } /** * Verify if we don't set {@link ReceiveOptions * are consuming events. */ @Test public void lastEnqueuedInformationIsNotUpdated() { final String firstPartition = "4"; final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final PartitionProperties properties = consumer.getPartitionProperties(firstPartition).block(TIMEOUT); Assertions.assertNotNull(properties); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(false); final AtomicBoolean isActive = new AtomicBoolean(true); final int expectedNumber = 5; final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final SendOptions sendOptions = new SendOptions().setPartitionId(firstPartition); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions)) .subscribe(sent -> logger.info("Event sent."), error -> logger.error("Error sending event", error)); try { StepVerifier.create(consumer.receiveFromPartition(firstPartition, position, options) .take(expectedNumber)) .assertNext(event -> Assertions.assertNull(event.getLastEnqueuedEventProperties(), "'lastEnqueuedEventProperties' should be null.")) .expectNextCount(expectedNumber - 1) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that each time we receive an event, the data, {@link ReceiveOptions * null as we are consuming events. */ @Test public void lastEnqueuedInformationIsUpdated() { final String partitionId = "3"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(partitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); try (EventHubConsumerAsyncClient consumer = builder.buildAsyncConsumerClient()) { final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); StepVerifier.create(consumer.receiveFromPartition(partitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true)) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); } } private static void verifyLastRetrieved(AtomicReference<LastEnqueuedEventProperties> atomicReference, LastEnqueuedEventProperties current, boolean isFirst) { Assertions.assertNotNull(current); final LastEnqueuedEventProperties previous = atomicReference.get(); atomicReference.set(current); if (isFirst) { return; } Assertions.assertNotNull(previous.getRetrievalTime(), "This is not the first event, should have a retrieval " + "time."); final int compared = previous.getRetrievalTime().compareTo(current.getRetrievalTime()); final int comparedSequenceNumber = previous.getOffset().compareTo(current.getOffset()); Assertions.assertTrue(compared <= 0, String.format("Expected retrieval time previous '%s' to be before or " + "equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); Assertions.assertTrue(comparedSequenceNumber <= 0, String.format("Expected offset previous '%s' to be before " + "or equal to current '%s'", previous.getRetrievalTime(), current.getRetrievalTime())); } /** * Verifies when a consumer with the same owner level takes over the consumption of events, the first consumer is * closed. */ @Test public void sameOwnerLevelClosesFirstConsumer() throws InterruptedException { final Semaphore semaphore = new Semaphore(1); final String lastPartition = "2"; final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now()); final ReceiveOptions firstReceive = new ReceiveOptions().setOwnerLevel(1L); final ReceiveOptions secondReceive = new ReceiveOptions().setOwnerLevel(2L); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicBoolean isActive = new AtomicBoolean(true); final Disposable.Composite subscriptions = Disposables.composite(); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); subscriptions.add(getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(lastPartition))) .subscribe(sent -> logger.info("Event sent."), error -> { logger.error("Error sending event", error); Assertions.fail("Should not have failed to publish event."); })); logger.info("STARTED CONSUMING FROM PARTITION 1"); semaphore.acquire(); subscriptions.add(consumer.receiveFromPartition(lastPartition, position, firstReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C1:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C1:\tERROR", ex); semaphore.release(); }, () -> { logger.info("C1:\tCompleted."); Assertions.fail("Should not be hitting this. An error should occur instead."); })); Thread.sleep(2000); logger.info("STARTED CONSUMING FROM PARTITION 1 with C3"); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); subscriptions.add(consumer2.receiveFromPartition(lastPartition, position, secondReceive) .filter(event -> TestUtils.isMatchingEvent(event, MESSAGE_TRACKING_ID)) .subscribe( event -> logger.info("C3:\tReceived event sequence: {}", event.getData().getSequenceNumber()), ex -> { logger.error("C3:\tERROR", ex); Assertions.fail("Should not error here"); }, () -> logger.info("C3:\tCompleted."))); try { Assertions.assertTrue(semaphore.tryAcquire(15, TimeUnit.SECONDS), "The EventHubConsumer was not closed after one with a higher epoch number started."); } finally { subscriptions.dispose(); isActive.set(false); dispose(producer, consumer, consumer2); } } /** * Verifies that we can get the metadata about an Event Hub */ @Test public void getEventHubProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getEventHubProperties()) .assertNext(properties -> { Assertions.assertNotNull(properties); Assertions.assertEquals(consumer.getEventHubName(), properties.getName()); Assertions.assertEquals(NUMBER_OF_PARTITIONS, properties.getPartitionIds().stream().count()); }).verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get the partition identifiers of an Event Hub. */ @Test public void getPartitionIds() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.getPartitionIds()) .expectNextCount(NUMBER_OF_PARTITIONS) .verifyComplete(); } finally { dispose(consumer); } } /** * Verifies that we can get partition information for each of the partitions in an Event Hub. */ @Test public void getPartitionProperties() { final EventHubConsumerAsyncClient consumer = createBuilder() .consumerGroup(DEFAULT_CONSUMER_GROUP_NAME) .buildAsyncConsumerClient(); try { for (String partitionId : EXPECTED_PARTITION_IDS) { StepVerifier.create(consumer.getPartitionProperties(partitionId)) .assertNext(properties -> { Assertions.assertEquals(consumer.getEventHubName(), properties.getEventHubName()); Assertions.assertEquals(partitionId, properties.getId()); }) .verifyComplete(); } } finally { dispose(consumer); } } /** * Verify that each time we receive an event, the data, and {@link ReceiveOptions * as we are consuming events. */ @Test public void canReceive() { final String secondPartitionId = "1"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final AtomicReference<LastEnqueuedEventProperties> lastViewed = new AtomicReference<>( new LastEnqueuedEventProperties(null, null, null, null)); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options).take(10)) .assertNext(event -> { final EventData eventData = event.getData(); Assertions.assertNotNull(eventData.getOffset(), "'getOffset' cannot be null."); Assertions.assertNotNull(eventData.getSequenceNumber(), "'getSequenceNumber' cannot be null."); Assertions.assertNotNull(eventData.getEnqueuedTime(), "'getEnqueuedTime' cannot be null."); Assertions.assertNotNull(eventData.getSystemProperties().get(OFFSET_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); Assertions.assertNotNull(eventData.getSystemProperties().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), true); }) .expectNextCount(5) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .assertNext(event -> verifyLastRetrieved(lastViewed, event.getLastEnqueuedEventProperties(), false)) .verifyComplete(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } @Test /** * Verifies we can receive from the same partition concurrently. */ @Test public void multipleReceiversSamePartition() throws InterruptedException { final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final EventHubConsumerAsyncClient consumer2 = builder.buildAsyncConsumerClient(); final String partitionId = "1"; final PartitionProperties properties = consumer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties, "Should have been able to get partition properties."); final int numberToTake = 10; final CountDownLatch countdown1 = new CountDownLatch(numberToTake); final CountDownLatch countdown2 = new CountDownLatch(numberToTake); final EventPosition position = EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber()); final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive).flatMap(event -> { event.getProperties().put(PARTITION_ID_HEADER, partitionId); return producer.send(event, new SendOptions().setPartitionId(partitionId)); }).subscribe( sent -> logger.info("Event sent."), error -> logger.error("Error sending event. Exception:" + error, error), () -> logger.info("Completed")); consumer.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer1: Event received"); countdown1.countDown(); }); consumer2.receiveFromPartition(partitionId, position) .filter(x -> TestUtils.isMatchingEvent(x.getData(), MESSAGE_TRACKING_ID)) .take(numberToTake) .subscribe(event -> { logger.info("Consumer2: Event received"); countdown2.countDown(); }); try { boolean successful = countdown1.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); boolean successful2 = countdown2.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); Assertions.assertTrue(successful, String.format("Expected to get %s events. Got: %s", numberToTake, countdown1.getCount())); Assertions.assertTrue(successful2, String.format("Expected to get %s events. Got: %s", numberToTake, countdown2.getCount())); } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); consumer2.close(); } } /** * Verifies that we are properly closing the receiver after each receive operation that terminates the upstream * flux. */ @Test void closesReceiver() throws InterruptedException { final String partitionId = "1"; final SendOptions sendOptions = new SendOptions().setPartitionId(partitionId); final EventHubConsumerAsyncClient consumer = builder.prefetchCount(1).buildAsyncConsumerClient(); final int numberOfEvents = 5; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final PartitionProperties properties = producer.getPartitionProperties(partitionId).block(TIMEOUT); Assertions.assertNotNull(properties); final AtomicReference<EventPosition> startingPosition = new AtomicReference<>( EventPosition.fromSequenceNumber(properties.getLastEnqueuedSequenceNumber())); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, sendOptions).thenReturn(Instant.now())) .subscribe(time -> logger.verbose("Sent event at: {}", time), error -> logger.error("Error sending event.", error), () -> logger.info("Completed")); try { for (int i = 0; i < 7; i++) { logger.info("[{}]: Starting iteration", i); final List<PartitionEvent> events = consumer.receiveFromPartition(partitionId, startingPosition.get()) .take(numberOfEvents) .collectList() .block(Duration.ofSeconds(15)); Thread.sleep(700); Assertions.assertNotNull(events); Assertions.assertEquals(numberOfEvents, events.size()); } } finally { isActive.set(false); producerEvents.dispose(); consumer.close(); } } /** * Verify that when we specify backpressure, events are no longer fetched after we've reached the subscribed * amount. */ @Test void canReceiveWithBackpressure() { final int backpressure = 15; final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final ReceiveOptions options = new ReceiveOptions() .setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient consumer = builder .prefetchCount(2) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest(), options), backpressure) .expectNextCount(backpressure) .thenAwait(Duration.ofSeconds(5)) .thenCancel() .verify(); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } /** * Verify that when we specify a small prefetch, it continues to fetch items. */ @Test void receivesWithSmallPrefetch() { final String secondPartitionId = "2"; final AtomicBoolean isActive = new AtomicBoolean(true); final EventHubProducerAsyncClient producer = builder.buildAsyncProducerClient(); final Disposable producerEvents = getEvents(isActive) .flatMap(event -> producer.send(event, new SendOptions().setPartitionId(secondPartitionId))) .subscribe( sent -> { }, error -> logger.error("Error sending event", error), () -> logger.info("Event sent.")); final int prefetch = 5; final int backpressure = 3; final int batchSize = 10; final EventHubConsumerAsyncClient consumer = builder .prefetchCount(prefetch) .buildAsyncConsumerClient(); try { StepVerifier.create(consumer.receiveFromPartition(secondPartitionId, EventPosition.latest()), prefetch) .expectNextCount(prefetch) .thenRequest(backpressure) .expectNextCount(backpressure) .thenRequest(batchSize) .expectNextCount(batchSize) .thenRequest(batchSize) .expectNextCount(batchSize) .thenAwait(Duration.ofSeconds(1)) .thenCancel() .verify(TIMEOUT); } finally { isActive.set(false); producerEvents.dispose(); dispose(producer, consumer); } } private static void assertPartitionEvent(PartitionEvent event, String eventHubName, Set<Integer> allPartitions, Set<Integer> expectedPartitions) { final PartitionContext context = event.getPartitionContext(); Assertions.assertEquals(eventHubName, context.getEventHubName()); final EventData eventData = event.getData(); final Integer partitionId = Integer.valueOf(context.getPartitionId()); Assertions.assertTrue(eventData.getProperties().containsKey(PARTITION_ID_HEADER)); final Object eventPartitionObject = eventData.getProperties().get(PARTITION_ID_HEADER); Assertions.assertTrue(eventPartitionObject instanceof Integer); final Integer eventPartition = (Integer) eventPartitionObject; Assertions.assertEquals(partitionId, eventPartition); Assertions.assertTrue(allPartitions.contains(partitionId)); expectedPartitions.remove(partitionId); } private Flux<EventData> getEvents(AtomicBoolean isActive) { return Flux.interval(Duration.ofMillis(500)) .takeWhile(count -> isActive.get()) .map(position -> TestUtils.getEvent("Event: " + position, MESSAGE_TRACKING_ID, position.intValue())); } }
This `accept` is now before `request.setBody(validateLength(request));`, will it be a problem?
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); if (options != null) { options.getRequestCallback().accept(request); Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } } context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
options.getRequestCallback().accept(request);
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); 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 ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
Hmm, that's a good question. For safety, given how late this change is going in, I'll have two if blocks to use the `RequestOptions`.
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); if (options != null) { options.getRequestCallback().accept(request); Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } } context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
options.getRequestCallback().accept(request);
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); 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 ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
can you rephrase this?
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); if (options != null) { Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } } context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); 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 ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
should there be a tracking issue referenced in the comment?
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); if (options != null) { Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } } context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); 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 ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
should we add a perf test for this? /cc @g2vinay
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); if (options != null) { Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } } context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
if (optionsContext != null && optionsContext != Context.NONE) {
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (request.getBody() != null) { request.setBody(validateLength(request)); } if (options != null) { options.getRequestCallback().accept(request); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); 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 ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && !options.isThrowOnError())) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
There is a lot of duplicated code here. Can we make this into a method?
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
final HttpHeaders supplementaryAuthHeaders = new HttpHeaders();
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus"; private static final String SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusSupplementaryAuthorization"; private static final String SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusDlqSupplementaryAuthorization"; private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; private final TokenCredential tokenCredential; /** * Creates a new instance with the given management client and serializer. * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * @param credential Credential to get additional tokens if necessary */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer, TokenCredential credential) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); this.tokenCredential = credential; } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardTo(String.format("https: createQueueOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(String.format("https: createQueueOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardTo(String.format("https: subscriptionOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(String.format("https: subscriptionOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscription.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardTo(String.format("https: subscription.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscription.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardDeadLetteredMessagesTo(String.format("https: subscription.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** Adds the additional authentication headers needed for various types of forwarding options. * * @param headerName Name of the auth header */ private void addAdditionalAuthHeader(String headerName, HttpHeaders headers) { final String scope; if (tokenCredential instanceof ServiceBusSharedKeyCredential) { scope = String.format("https: } else { scope = ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE; } final Mono<AccessToken> tokenMono = tokenCredential.getToken(new TokenRequestContext().addScopes(scope)); final AccessToken token = tokenMono.block(ServiceBusConstants.OPERATION_TIMEOUT); if (headers == null || token == null) { return; } headers.add(headerName, token.getToken()); } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
Use a string constant?
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
queue.setForwardTo(String.format("https:
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus"; private static final String SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusSupplementaryAuthorization"; private static final String SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusDlqSupplementaryAuthorization"; private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; private final TokenCredential tokenCredential; /** * Creates a new instance with the given management client and serializer. * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * @param credential Credential to get additional tokens if necessary */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer, TokenCredential credential) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); this.tokenCredential = credential; } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardTo(String.format("https: createQueueOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(String.format("https: createQueueOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardTo(String.format("https: subscriptionOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(String.format("https: subscriptionOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscription.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardTo(String.format("https: subscription.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscription.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardDeadLetteredMessagesTo(String.format("https: subscription.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** Adds the additional authentication headers needed for various types of forwarding options. * * @param headerName Name of the auth header */ private void addAdditionalAuthHeader(String headerName, HttpHeaders headers) { final String scope; if (tokenCredential instanceof ServiceBusSharedKeyCredential) { scope = String.format("https: } else { scope = ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE; } final Mono<AccessToken> tokenMono = tokenCredential.getToken(new TokenRequestContext().addScopes(scope)); final AccessToken token = tokenMono.block(ServiceBusConstants.OPERATION_TIMEOUT); if (headers == null || token == null) { return; } headers.add(headerName, token.getToken()); } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
Q: also should we be using a UriBuilder instead of concatenated strings?
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
queue.setForwardTo(String.format("https:
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus"; private static final String SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusSupplementaryAuthorization"; private static final String SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusDlqSupplementaryAuthorization"; private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; private final TokenCredential tokenCredential; /** * Creates a new instance with the given management client and serializer. * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * @param credential Credential to get additional tokens if necessary */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer, TokenCredential credential) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); this.tokenCredential = credential; } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardTo(String.format("https: createQueueOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(String.format("https: createQueueOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardTo(String.format("https: subscriptionOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(String.format("https: subscriptionOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscription.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardTo(String.format("https: subscription.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscription.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardDeadLetteredMessagesTo(String.format("https: subscription.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** Adds the additional authentication headers needed for various types of forwarding options. * * @param headerName Name of the auth header */ private void addAdditionalAuthHeader(String headerName, HttpHeaders headers) { final String scope; if (tokenCredential instanceof ServiceBusSharedKeyCredential) { scope = String.format("https: } else { scope = ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE; } final Mono<AccessToken> tokenMono = tokenCredential.getToken(new TokenRequestContext().addScopes(scope)); final AccessToken token = tokenMono.block(ServiceBusConstants.OPERATION_TIMEOUT); if (headers == null || token == null) { return; } headers.add(headerName, token.getToken()); } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
was going for simplicity here following the pattern in other methods, but refactored it some more so that the core modifer methods are in one place
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
final HttpHeaders supplementaryAuthHeaders = new HttpHeaders();
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus"; private static final String SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusSupplementaryAuthorization"; private static final String SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusDlqSupplementaryAuthorization"; private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; private final TokenCredential tokenCredential; /** * Creates a new instance with the given management client and serializer. * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * @param credential Credential to get additional tokens if necessary */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer, TokenCredential credential) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); this.tokenCredential = credential; } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardTo(String.format("https: createQueueOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(String.format("https: createQueueOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardTo(String.format("https: subscriptionOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(String.format("https: subscriptionOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscription.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardTo(String.format("https: subscription.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscription.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardDeadLetteredMessagesTo(String.format("https: subscription.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** Adds the additional authentication headers needed for various types of forwarding options. * * @param headerName Name of the auth header */ private void addAdditionalAuthHeader(String headerName, HttpHeaders headers) { final String scope; if (tokenCredential instanceof ServiceBusSharedKeyCredential) { scope = String.format("https: } else { scope = ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE; } final Mono<AccessToken> tokenMono = tokenCredential.getToken(new TokenRequestContext().addScopes(scope)); final AccessToken token = tokenMono.block(ServiceBusConstants.OPERATION_TIMEOUT); if (headers == null || token == null) { return; } headers.add(headerName, token.getToken()); } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
went with the UrlBuilder in azure core. It is an overkill here, but this should cover us in case of any future expansions
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
queue.setForwardTo(String.format("https:
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus"; private static final String SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusSupplementaryAuthorization"; private static final String SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME = "ServiceBusDlqSupplementaryAuthorization"; private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; private final TokenCredential tokenCredential; /** * Creates a new instance with the given management client and serializer. * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * @param credential Credential to get additional tokens if necessary */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer, TokenCredential credential) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); this.tokenCredential = credential; } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardTo(String.format("https: createQueueOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(createQueueOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(String.format("https: createQueueOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardTo(String.format("https: subscriptionOptions.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscriptionOptions.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(String.format("https: subscriptionOptions.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(queue.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardTo(String.format("https: queue.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(queue.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); queue.setForwardDeadLetteredMessagesTo(String.format("https: queue.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final HttpHeaders supplementaryAuthHeaders = new HttpHeaders(); Context additionalContext = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); if (!CoreUtils.isNullOrEmpty(subscription.getForwardTo())) { addAdditionalAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardTo(String.format("https: subscription.getForwardTo())); } if (!CoreUtils.isNullOrEmpty(subscription.getForwardDeadLetteredMessagesTo())) { addAdditionalAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, supplementaryAuthHeaders); subscription.setForwardDeadLetteredMessagesTo(String.format("https: subscription.getForwardDeadLetteredMessagesTo())); } if (supplementaryAuthHeaders.getSize() != 0) { additionalContext = additionalContext.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, supplementaryAuthHeaders); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", additionalContext) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** Adds the additional authentication headers needed for various types of forwarding options. * * @param headerName Name of the auth header */ private void addAdditionalAuthHeader(String headerName, HttpHeaders headers) { final String scope; if (tokenCredential instanceof ServiceBusSharedKeyCredential) { scope = String.format("https: } else { scope = ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE; } final Mono<AccessToken> tokenMono = tokenCredential.getToken(new TokenRequestContext().addScopes(scope)); final AccessToken token = tokenMono.block(ServiceBusConstants.OPERATION_TIMEOUT); if (headers == null || token == null) { return; } headers.add(headerName, token.getToken()); } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
same with using fluentAPI
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders());
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .map(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } return null; }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
I don't believe this is the right operator. Mapping is a transform, I wouldn't want it to return null if the AZURE_REQUEST_HTTP_HEADERS_KEY existed but were another object type ```java context.getData("foo").ifPresent(value -> { if (!(value instanceof HttpHeaders)) { return; } HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); }); ```
private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .map(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } return null; }); }
.map(headers -> {
private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
Would this be a fatal error? Do we want to silently continue if we were unable to create a URL instead of returning null? Could the user recover from this?
private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; }
logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'",
private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .map(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } return null; }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
If we fail in constructing a URL, then by returning the null the rest of the request should go through, and the user will be able to set the forwarding using portal/cli/update queue API
private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; }
logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'",
private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .map(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } return null; }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
done
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders());
return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .map(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } return null; }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); } /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
makes sense, reduced it to ifpresent
private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .map(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } return null; }); }
.map(headers -> {
private void addSupplementaryAuthHeader(String headerName, String entity, Context context) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY) .ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; customHttpHeaders.add(headerName, entity); } }); }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithTrace = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final Context contextWithHeaders = contextWithTrace.addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
class ServiceBusAdministrationAsyncClient { private static final String CONTENT_TYPE = "application/xml"; private static final String QUEUES_ENTITY_TYPE = "queues"; private static final String TOPICS_ENTITY_TYPE = "topics"; private static final int NUMBER_OF_ELEMENTS = 100; private final ServiceBusManagementClientImpl managementClient; private final EntitiesImpl entityClient; private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class); private final ServiceBusManagementSerializer serializer; private final RulesImpl rulesClient; /** * Creates a new instance with the given management client and serializer. * * @param managementClient Client to make management calls. * @param serializer Serializer to deserialize ATOM XML responses. * * @throws NullPointerException if any one of {@code managementClient, serializer, credential} is null. */ ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient, ServiceBusManagementSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null."); this.entityClient = managementClient.getEntities(); this.rulesClient = managementClient.getRules(); } /** * Creates a queue with the given name. * * @param queueName Name of the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceExistsException if a queue exists with the same {@code queueName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName) { try { return createQueue(queueName, new CreateQueueOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a queue with the {@link CreateQueueOptions} and given queue name. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that completes with information about the created queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) { return createQueueWithResponse(queueName, queueOptions).map(Response::getValue); } /** * Creates a queue and returns the created queue in addition to the HTTP response. * * @param queueName Name of the queue to create. * @param queueOptions Options about the queue to create. * * @return A Mono that returns the created queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} or {@code queueOptions} is null. * @throws ResourceExistsException if a queue exists with the same {@link QueueProperties * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) { return withContext(context -> createQueueWithResponse(queueName, queueOptions, context)); } /** * Creates a rule under the given topic and subscription * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code ruleName} are are null. * @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) { try { return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a rule with the {@link CreateRuleOptions}. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that completes with information about the created rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions) .map(Response::getValue); } /** * Creates a rule and returns the created rule in addition to the HTTP response. * * @param topicName Name of the topic associated with rule. * @param subscriptionName Name of the subscription associated with the rule. * @param ruleName Name of the rule. * @param ruleOptions Information about the rule to create. * * @return A Mono that returns the created rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions} * are are null. * @throws ResourceExistsException if a rule exists with the same topic and rule name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions) { return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions, context)); } /** * Creates a subscription with the given topic and subscription names. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) { try { return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a subscription with the {@link CreateSubscriptionOptions}. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that completes with information about the created subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions) .map(Response::getValue); } /** * Creates a subscription and returns the created subscription in addition to the HTTP response. * * @param topicName Name of the topic associated with subscription. * @param subscriptionName Name of the subscription. * @param subscriptionOptions Information about the subscription to create. * * @return A Mono that returns the created subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred * processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions} * are are null. * @throws ResourceExistsException if a subscription exists with the same topic and subscription name. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions) { return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions, context)); } /** * Creates a topic with the given name. * * @param topicName Name of the topic to create. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName) { try { return createTopic(topicName, new CreateTopicOptions()); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Creates a topic with the {@link CreateTopicOptions}. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that completes with information about the created topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) { return createTopicWithResponse(topicName, topicOptions).map(Response::getValue); } /** * Creates a topic and returns the created topic in addition to the HTTP response. * * @param topicName Name of the topic to create. * @param topicOptions The options used to create the topic. * * @return A Mono that returns the created topic in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topicName} or {@code topicOptions} is null. * @throws ResourceExistsException if a topic exists with the same {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) { return withContext(context -> createTopicWithResponse(topicName, topicOptions, context)); } /** * Deletes a queue the matching {@code queueName}. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteQueue(String queueName) { return deleteQueueWithResponse(queueName).then(); } /** * Deletes a queue the matching {@code queueName} and returns the HTTP response. * * @param queueName Name of queue to delete. * * @return A Mono that completes when the queue is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws NullPointerException if {@code queueName} is null. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteQueueWithResponse(String queueName) { return withContext(context -> deleteQueueWithResponse(queueName, context)); } /** * Deletes a rule the matching {@code ruleName}. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) { return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then(); } /** * Deletes a rule the matching {@code ruleName} and returns the HTTP response. * * @param topicName Name of topic associated with rule to delete. * @param subscriptionName Name of the subscription associated with the rule to delete. * @param ruleName Name of rule to delete. * * @return A Mono that completes when the rule is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an * empty string. * @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null. * @throws ResourceNotFoundException if the {@code ruleName} does not exist. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Deletes a subscription the matching {@code subscriptionName}. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteSubscription(String topicName, String subscriptionName) { return deleteSubscriptionWithResponse(topicName, subscriptionName).then(); } /** * Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * * @return A Mono that completes when the subscription is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context)); } /** * Deletes a topic the matching {@code topicName}. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteTopic(String topicName) { return deleteTopicWithResponse(topicName).then(); } /** * Deletes a topic the matching {@code topicName} and returns the HTTP response. * * @param topicName Name of topic to delete. * * @return A Mono that completes when the topic is deleted and returns the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTopicWithResponse(String topicName) { return withContext(context -> deleteTopicWithResponse(topicName, context)); } /** * Gets information about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> getQueue(String queueName) { return getQueueWithResponse(queueName).map(Response::getValue); } /** * Gets information about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with information about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, Function.identity())); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getQueueExists(String queueName) { return getQueueExistsWithResponse(queueName).map(Response::getValue); } /** * Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace. * * @param queueName Name of the queue. * * @return A Mono that completes indicating whether or not the queue exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) { return getEntityExistsWithResponse(getQueueWithResponse(queueName)); } /** * Gets runtime properties about the queue. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) { return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue()); } /** * Gets runtime properties about the queue along with its HTTP response. * * @param queueName Name of queue to get information about. * * @return A Mono that completes with runtime properties about the queue and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code queueName} is an empty string. * @throws NullPointerException if {@code queueName} is null. * @throws ResourceNotFoundException if the {@code queueName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) { return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new)); } /** * Gets information about the Service Bus namespace. * * @return A Mono that completes with information about the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to the namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<NamespaceProperties> getNamespaceProperties() { return getNamespacePropertiesWithResponse().map(Response::getValue); } /** * Gets information about the Service Bus namespace along with its HTTP response. * * @return A Mono that completes with information about the namespace and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() { return withContext(this::getNamespacePropertiesWithResponse); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) { return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue()); } /** * Gets a rule from the service namespace. * * Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double, * and OffsetDateTime. Other data types would return its string value. * * @param topicName The name of the topic relative to service bus namespace. * @param subscriptionName The subscription name the rule belongs to. * @param ruleName The name of the rule to retrieve. * * @return The associated rule with the corresponding HTTP response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName) { return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context)); } /** * Gets information about the queue. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) { return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets information about the subscription along with its HTTP response. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with information about the subscription and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, Function.identity())); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) { return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue); } /** * Gets whether or not a subscription within a topic exists. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of the subscription. * * @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) { return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName)); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties( String topicName, String subscriptionName) { return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName) .map(response -> response.getValue()); } /** * Gets runtime properties about the subscription. * * @param topicName Name of topic associated with subscription. * @param subscriptionName Name of subscription to get information about. * * @return A Mono that completes with runtime properties about the subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code subscriptionName} is an empty string. * @throws NullPointerException if {@code subscriptionName} is null. * @throws ResourceNotFoundException if the {@code subscriptionName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse( String topicName, String subscriptionName) { return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context, SubscriptionRuntimeProperties::new)); } /** * Gets information about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> getTopic(String topicName) { return getTopicWithResponse(topicName).map(Response::getValue); } /** * Gets information about the topic along with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with information about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, Function.identity())); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Boolean> getTopicExists(String topicName) { return getTopicExistsWithResponse(topicName).map(Response::getValue); } /** * Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace. * * @param topicName Name of the topic. * * @return A Mono that completes indicating whether or not the topic exists along with its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) { return getEntityExistsWithResponse(getTopicWithResponse(topicName)); } /** * Gets runtime properties about the topic. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) { return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue()); } /** * Gets runtime properties about the topic with its HTTP response. * * @param topicName Name of topic to get information about. * * @return A Mono that completes with runtime properties about the topic and the associated HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If error occurred processing the request. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @throws NullPointerException if {@code topicName} is null. * @throws ResourceNotFoundException if the {@code topicName} does not exist. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) { return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new)); } /** * Fetches all the queues in the Service Bus namespace. * * @return A Flux of {@link QueueProperties queues} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<QueueProperties> listQueues() { return new PagedFlux<>( () -> withContext(context -> listQueuesFirstPage(context)), token -> withContext(context -> listQueuesNextPage(token, context))); } /** * Fetches all the rules for a topic and subscription. * * @param topicName The topic name under which all the rules need to be retrieved. * @param subscriptionName The name of the subscription for which all rules need to be retrieved. * * @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null. * @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)), token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context))); } /** * Fetches all the subscriptions for a topic. * * @param topicName The topic name under which all the subscriptions need to be retrieved. * * @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws NullPointerException if {@code topicName} is null. * @throws IllegalArgumentException if {@code topicName} is an empty string. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) { if (topicName == null) { return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } return new PagedFlux<>( () -> withContext(context -> listSubscriptionsFirstPage(topicName, context)), token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context))); } /** * Fetches all the topics in the Service Bus namespace. * * @return A Flux of {@link TopicProperties topics} in the Service Bus namespace. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @see <a href="https: * authorization rules</a> */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<TopicProperties> listTopics() { return new PagedFlux<>( () -> withContext(context -> listTopicsFirstPage(context)), token -> withContext(context -> listTopicsNextPage(token, context))); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated queue. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueProperties> updateQueue(QueueProperties queue) { return updateQueueWithResponse(queue).map(Response::getValue); } /** * Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link QueueProperties * <li>{@link QueueProperties * <li>{@link QueueProperties * </li> * <li>{@link QueueProperties * </ul> * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated queue in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error * occurred processing the request. * @throws NullPointerException if {@code queue} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) { return withContext(context -> updateQueueWithResponse(queue, context)); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) { return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue); } /** * Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all * of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * @param topicName The topic name under which the rule is updated. * @param subscriptionName The name of the subscription for which the rule is updated. * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated rule in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link RuleProperties * @throws NullPointerException if {@code rule} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule) { return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context)); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) { return updateSubscriptionWithResponse(subscription).map(Response::getValue); } /** * Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be * fully populated as all of the properties are replaced. If a property is not set the service default value is * used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * <li>{@link SubscriptionProperties * </ul> * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that returns the updated subscription in addition to the HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an * error occurred processing the request. * @throws IllegalArgumentException if {@link SubscriptionProperties * SubscriptionProperties * @throws NullPointerException if {@code subscription} is null. * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse( SubscriptionProperties subscription) { return withContext(context -> updateSubscriptionWithResponse(subscription, context)); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<TopicProperties> updateTopic(TopicProperties topic) { return updateTopicWithResponse(topic).map(Response::getValue); } /** * Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as * all of the properties are replaced. If a property is not set the service default value is used. * * The suggested flow is: * <ol> * <li>{@link * <li>Update the required elements.</li> * <li>Pass the updated description into this method.</li> * </ol> * * <p> * There are a subset of properties that can be updated. More information can be found in the links below. They are: * <ul> * <li>{@link TopicProperties * <li>{@link TopicProperties * </li> * </ul> * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * * @return A Mono that completes with the updated topic and its HTTP response. * @throws ClientAuthenticationException if the client's credentials do not have access to modify the * namespace. * @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error * occurred processing the request. * @throws IllegalArgumentException if {@link TopicProperties * string. * @throws NullPointerException if {@code topic} is null. * @see <a href="https: * @see <a href="https: */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) { return withContext(context -> updateTopicWithResponse(topic, context)); } /** * Creates a queue with its context. * * @param createQueueOptions Queue to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null.")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } if (createQueueOptions == null) { return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = createQueueOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); createQueueOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = createQueueOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); createQueueOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(description); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queueName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeQueue); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a rule with its context. * * @param ruleOptions Rule to create. * @param context Context to pass into request. * * * @return A Mono that completes with the created {@link RuleProperties}. */ Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName, CreateRuleOptions ruleOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null.")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty.")); } if (ruleOptions == null) { return monoError(logger, new NullPointerException("'rule' cannot be null.")); } final RuleActionImpl action = ruleOptions.getAction() != null ? EntityHelper.toImplementation(ruleOptions.getAction()) : null; final RuleFilterImpl filter = ruleOptions.getFilter() != null ? EntityHelper.toImplementation(ruleOptions.getFilter()) : null; final RuleDescription rule = new RuleDescription() .setAction(action) .setFilter(filter) .setName(ruleName); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(rule); final CreateRuleBody createEntity = new CreateRuleBody().setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a subscription with its context. * * @param subscriptionOptions Subscription to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName, CreateSubscriptionOptions subscriptionOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty.")); } if (subscriptionOptions == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscriptionOptions.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscriptionOptions.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscriptionOptions.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscriptionOptions.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(subscription); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, null, contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a topicOptions with its context. * * @param topicOptions Topic to create. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } if (topicOptions == null) { return monoError(logger, new NullPointerException("'topicOptions' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(topic); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeTopic); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param queueName Name of queue to delete. * @param context Context to pass into request. * * @return A Mono that completes when the queue is deleted. */ Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(queueName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a queue with its context. * * @param topicName Name of topic to delete. * @param subscriptionName Name of the subscription for the rule. * @param ruleName Name of the rule. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link QueueProperties}. */ Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (ruleName == null) { return monoError(logger, new NullPointerException("'ruleName' cannot be null")); } else if (ruleName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a subscription with its context. * * @param topicName Name of topic associated with subscription to delete. * @param subscriptionName Name of subscription to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link SubscriptionProperties}. */ Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) { if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a topic with its context. * * @param topicName Name of topic to delete. * @param context Context to pass into request. * * @return A Mono that completes with the created {@link TopicProperties}. */ Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.deleteWithResponseAsync(topicName, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets whether an entity exists. * * @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is * thrown, then it is mapped to false. * @param <T> Entity type. * * @return True if the entity exists, false otherwise. */ <T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) { return getEntityOperation.map(response -> { final boolean exists = response.getValue() != null; return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), exists); }) .onErrorResume(ResourceNotFoundException.class, exception -> { final HttpResponse response = exception.getResponse(); final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false); return Mono.just(result); }); } /** * Gets a queue with its context. * * @param queueName Name of queue to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link QueueProperties}. */ <T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context, Function<QueueProperties, T> mapper) { if (queueName == null) { return monoError(logger, new NullPointerException("'queueName' cannot be null")); } else if (queueName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(queueName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<QueueProperties> deserialize = deserializeQueue(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName, String ruleName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(this::deserializeRule); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets a subscription with its context. * * @param topicName Name of the topic associated with the subscription. * @param subscriptionName Name of subscription to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link SubscriptionProperties}. */ <T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context, Function<SubscriptionProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null.")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string.")); } else if (subscriptionName == null) { return monoError(logger, new NullPointerException("'subscriptionName' cannot be null.")); } else if (subscriptionName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format( "Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the namespace properties with its context. * * @param context Context to pass into request. * * @return A Mono that completes with the {@link NamespaceProperties}. */ Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) { return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> { final NamespacePropertiesEntry entry = response.getValue(); if (entry == null || entry.getContent() == null) { sink.error(new AzureException( "There was no content inside namespace response. Entry: " + response)); return; } final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties(); final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), namespaceProperties); sink.next(result); }); } /** * Gets a topic with its context. * * @param topicName Name of topic to fetch information for. * @param context Context to pass into request. * * @return A Mono that completes with the {@link TopicProperties}. */ <T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context, Function<TopicProperties, T> mapper) { if (topicName == null) { return monoError(logger, new NullPointerException("'topicName' cannot be null")); } else if (topicName.isEmpty()) { return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty.")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.getWithResponseAsync(topicName, true, withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .handle((response, sink) -> { final Response<TopicProperties> deserialize = deserializeTopic(response); if (deserialize.getValue() == null) { final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize); sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName), notFoundResponse)); } else { final T mapped = mapper.apply(deserialize.getValue()); sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), mapped)); } }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Gets the first page of queues with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of queues. */ Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listQueues(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of queues with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of queues or empty if there are no items left. */ Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listQueues(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of rules with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of rules. */ Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listRules(topicName, subscriptionName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of rules with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of rules or empty if there are no items left. */ Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listRules(topicName, subscriptionName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of subscriptions with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listSubscriptions(topicName, 0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of subscriptions with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of subscriptions or empty if there are no items left. */ Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listSubscriptions(topicName, skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the first page of topics with context. * * @param context Context to pass into request. * * @return A Mono that completes with a page of topics. */ Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return listTopics(0, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Gets the next page of topics with context. * * @param continuationToken Number of items to skip in feed. * @param context Context to pass into request. * * @return A Mono that completes with a page of topics or empty if there are no items left. */ Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } try { final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); final int skip = Integer.parseInt(continuationToken); return listTopics(skip, withTracing); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Updates a queue with its context. * * @param queue Information about the queue to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link QueueProperties}. */ Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) { if (queue == null) { return monoError(logger, new NullPointerException("'queue' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = queue.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); queue.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = queue.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); queue.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final QueueDescription queueDescription = EntityHelper.toImplementation(queue); final CreateQueueBodyContent content = new CreateQueueBodyContent() .setType(CONTENT_TYPE) .setQueueDescription(queueDescription); final CreateQueueBody createEntity = new CreateQueueBody() .setContent(content); try { return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeQueue(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a rule with its context. * * @param rule Information about the rule to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link RuleProperties}. */ Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName, RuleProperties rule, Context context) { if (rule == null) { return monoError(logger, new NullPointerException("'rule' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final RuleDescription implementation = EntityHelper.toImplementation(rule); final CreateRuleBodyContent content = new CreateRuleBodyContent() .setType(CONTENT_TYPE) .setRuleDescription(implementation); final CreateRuleBody ruleBody = new CreateRuleBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(), ruleBody, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeRule(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a subscription with its context. * * @param subscription Information about the subscription to update. You must provide all the property values * that are desired on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link SubscriptionProperties}. */ Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription, Context context) { if (subscription == null) { return monoError(logger, new NullPointerException("'subscription' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final Context contextWithHeaders = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE) .addData(AZURE_REQUEST_HTTP_HEADERS_KEY, new HttpHeaders()); final String forwardToEntity = subscription.getForwardTo(); if (!CoreUtils.isNullOrEmpty(forwardToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardToEntity, contextWithHeaders); subscription.setForwardTo(getAbsoluteUrlFromEntity(forwardToEntity)); } final String forwardDlqToEntity = subscription.getForwardDeadLetteredMessagesTo(); if (!CoreUtils.isNullOrEmpty(forwardDlqToEntity)) { addSupplementaryAuthHeader(SERVICE_BUS_DLQ_SUPPLEMENTARY_AUTHORIZATION_HEADER_NAME, forwardDlqToEntity, contextWithHeaders); subscription.setForwardDeadLetteredMessagesTo(getAbsoluteUrlFromEntity(forwardDlqToEntity)); } final String topicName = subscription.getTopicName(); final String subscriptionName = subscription.getSubscriptionName(); final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription); final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent() .setType(CONTENT_TYPE) .setSubscriptionDescription(implementation); final CreateSubscriptionBody createEntity = new CreateSubscriptionBody() .setContent(content); try { return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity, "*", contextWithHeaders) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeSubscription(topicName, response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Updates a topic with its context. * * @param topic Information about the topic to update. You must provide all the property values that are desired * on the updated entity. Any values not provided are set to the service default values. * @param context Context to pass into request. * * @return A Mono that completes with the updated {@link TopicProperties}. */ Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) { if (topic == null) { return monoError(logger, new NullPointerException("'topic' cannot be null")); } else if (context == null) { return monoError(logger, new NullPointerException("'context' cannot be null.")); } final TopicDescription implementation = EntityHelper.toImplementation(topic); final CreateTopicBodyContent content = new CreateTopicBodyContent() .setType(CONTENT_TYPE) .setTopicDescription(implementation); final CreateTopicBody createEntity = new CreateTopicBody() .setContent(content); final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, AZ_TRACING_NAMESPACE_VALUE); try { return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .map(response -> deserializeTopic(response)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private <T> T deserialize(Object object, Class<T> clazz) { if (object == null) { return null; } final String contents = String.valueOf(object); if (contents.isEmpty()) { return null; } try { return serializer.deserialize(contents, clazz); } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e)); } } /** * Given an HTTP response, will deserialize it into a strongly typed Response object. * * @param response HTTP response to deserialize response body from. * @param clazz Class to deserialize response type into. * @param <T> Class type to deserialize response into. * * @return A Response with a strongly typed response value. */ private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) { final T deserialize = deserialize(response.getValue(), clazz); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), deserialize); } /** * Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<QueueProperties> deserializeQueue(Response<Object> response) { final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getQueueDescription() == null) { final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) { logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription()); final String queueName = getTitleValue(entry.getTitle()); EntityHelper.setQueueName(result, queueName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<RuleProperties> deserializeRule(Response<Object> response) { final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.info("entry.getContent() is null. The entity may not exist. {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final RuleDescription description = entry.getContent().getRuleDescription(); final RuleProperties result = EntityHelper.toModel(description); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link * SubscriptionProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) { final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } final SubscriptionProperties subscription = EntityHelper.toModel( entry.getContent().getSubscriptionDescription()); final String subscriptionName = getTitleValue(entry.getTitle()); EntityHelper.setSubscriptionName(subscription, subscriptionName); EntityHelper.setTopicName(subscription, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), subscription); } /** * Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link * QueueProperties}. * * @param response HTTP Response to deserialize. * * @return The corresponding HTTP response with convenience properties set. */ private Response<TopicProperties> deserializeTopic(Response<Object> response) { final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class); if (entry == null) { return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent() == null) { logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else if (entry.getContent().getTopicDescription() == null) { final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class); if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) { logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } } final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription()); final String topicName = getTitleValue(entry.getTitle()); EntityHelper.setTopicName(result, topicName); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result); } /** * Creates a {@link FeedPage} given the elements and a set of response links to get the next link from. * * @param entities Entities in the feed. * @param responseLinks Links returned from the feed. * @param <TResult> Type of Service Bus entities in page. * * @return A {@link FeedPage} indicating whether this can be continued or not. * @throws MalformedURLException if the "next" page link does not contain a well-formed URL. */ private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities, List<ResponseLink> responseLinks) throws MalformedURLException, UnsupportedEncodingException { final Optional<ResponseLink> nextLink = responseLinks.stream() .filter(link -> link.getRel().equalsIgnoreCase("next")) .findFirst(); if (!nextLink.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } final URL url = new URL(nextLink.get().getHref()); final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name()); final Optional<Integer> skipParameter = Arrays.stream(decode.split("&amp;|&")) .map(part -> part.split("=", 2)) .filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2) .map(parts -> Integer.valueOf(parts[1])) .findFirst(); if (skipParameter.isPresent()) { return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities, skipParameter.get()); } else { logger.warning("There should have been a skip parameter for the next page."); return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities); } } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of queues. */ private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class); final QueueDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<QueueProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null) .map(e -> { final String queueName = getTitleValue(e.getTitle()); final QueueProperties queueProperties = EntityHelper.toModel( e.getContent().getQueueDescription()); EntityHelper.setQueueName(queueProperties, queueName); return queueProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of rules. */ private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip, Context context) { return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<RuleDescriptionFeed> feedResponse = deserialize(response, RuleDescriptionFeed.class); final RuleDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<RuleProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null) .map(e -> { return EntityHelper.toModel(e.getContent().getRuleDescription()); }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<RuleDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of subscriptions. */ private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip, Context context) { return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response, SubscriptionDescriptionFeed.class); final SubscriptionDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<SubscriptionProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null) .map(e -> { final String subscriptionName = getTitleValue(e.getTitle()); final SubscriptionProperties description = EntityHelper.toModel( e.getContent().getSubscriptionDescription()); EntityHelper.setTopicName(description, topicName); EntityHelper.setSubscriptionName(description, subscriptionName); return description; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException( "Could not parse response into FeedPage<SubscriptionDescription>", error)); } }); } /** * Helper method that invokes the service method, extracts the data and translates it to a PagedResponse. * * @param skip Number of elements to skip. * @param context Context for the query. * * @return A Mono that completes with a paged response of topics. */ private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) { return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context) .onErrorMap(ServiceBusAdministrationAsyncClient::mapException) .flatMap(response -> { final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class); final TopicDescriptionFeed feed = feedResponse.getValue(); if (feed == null) { logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip, NUMBER_OF_ELEMENTS); return Mono.empty(); } final List<TopicProperties> entities = feed.getEntry().stream() .filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null) .map(e -> { final String topicName = getTitleValue(e.getTitle()); final TopicProperties topicProperties = EntityHelper.toModel( e.getContent().getTopicDescription()); EntityHelper.setTopicName(topicProperties, topicName); return topicProperties; }) .collect(Collectors.toList()); try { return Mono.just(extractPage(feedResponse, entities, feed.getLink())); } catch (MalformedURLException | UnsupportedEncodingException error) { return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>", error)); } }); } /** * Check that the additional headers field is present and add the additional auth header * * @param headerName name of the header to be added * @param context current request context * * @return boolean representing the outcome of adding header operation */ /** * Checks if the given entity is an absolute URL, if so return it. * Otherwise, construct the URL from the given entity and return that. * * @param entity : entity to forward messages to. * * @return Forward to Entity represented as an absolute URL */ private String getAbsoluteUrlFromEntity(String entity) { try { URL url = new URL(entity); return url.toString(); } catch (MalformedURLException ex) { } UrlBuilder urlBuilder = new UrlBuilder(); urlBuilder.setScheme("https"); urlBuilder.setHost(managementClient.getEndpoint()); urlBuilder.setPath(entity); try { URL url = urlBuilder.toUrl(); return url.toString(); } catch (MalformedURLException ex) { logger.error("Failed to construct URL using the endpoint:'{}' and entity:'{}'", managementClient.getEndpoint(), entity); logger.logThrowableAsError(ex); } return null; } /** * Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text * is represented as an entry with an empty string as the key. * * For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName". * * @param responseTitle XML title element. * * @return The XML text inside the title. {@code null} is returned if there is no value. */ @SuppressWarnings("unchecked") private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } } /** * Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}. * * @param exception Exception from the ATOM API. * * @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link * ServiceBusManagementErrorException}. */ private static Throwable mapException(Throwable exception) { if (!(exception instanceof ServiceBusManagementErrorException)) { return exception; } final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception); final ServiceBusManagementError error = managementError.getValue(); final HttpResponse errorHttpResponse = managementError.getResponse(); final int statusCode = error != null && error.getCode() != null ? error.getCode() : errorHttpResponse.getStatusCode(); final String errorDetail = error != null && error.getDetail() != null ? error.getDetail() : managementError.getMessage(); switch (statusCode) { case 401: return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception); case 404: return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception); case 409: return new ResourceExistsException(errorDetail, managementError.getResponse(), exception); case 412: return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception); default: return new HttpResponseException(errorDetail, managementError.getResponse(), exception); } } /** * A page of Service Bus entities. * * @param <T> The entity description from Service Bus. */ private static final class FeedPage<T> implements PagedResponse<T> { private final int statusCode; private final HttpHeaders header; private final HttpRequest request; private final IterableStream<T> entries; private final String continuationToken; /** * Creates a page that does not have any more pages. * * @param entries Items in the page. */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = null; } /** * Creates an instance that has additional pages to fetch. * * @param entries Items in the page. * @param skip Number of elements to "skip". */ private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) { this.statusCode = statusCode; this.header = header; this.request = request; this.entries = new IterableStream<>(entries); this.continuationToken = String.valueOf(skip); } @Override public IterableStream<T> getElements() { return entries; } @Override public String getContinuationToken() { return continuationToken; } @Override public int getStatusCode() { return statusCode; } @Override public HttpHeaders getHeaders() { return header; } @Override public HttpRequest getRequest() { return request; } @Override public void close() { } } private static final class EntityNotFoundHttpResponse<T> extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private EntityNotFoundHttpResponse(Response<T> response) { super(response.getRequest()); this.headers = response.getHeaders(); this.statusCode = response.getStatusCode(); } @Override public int getStatusCode() { return statusCode; } @Override public String getHeaderValue(String name) { return headers.getValue(name); } @Override public HttpHeaders getHeaders() { return headers; } @Override public Flux<ByteBuffer> getBody() { return Flux.empty(); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.empty(); } @Override public Mono<String> getBodyAsString() { return Mono.empty(); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.empty(); } } }
@conniey should these services be moved to a team-wide resource (not something with coniey)?
void deserializeSubscriptionDescriptionFeed() throws IOException { final String contents = getContents("SubscriptionDescriptionFeed.xml"); final List<ResponseLink> responseLinks = Collections.singletonList( new ResponseLink().setRel("self") .setHref("https: ); final String topicName = "topic"; final String subscriptionName1 = "subscription-0"; final String subscriptionName2 = "subscription-session-0"; final String subscriptionName3 = "subscription-session-1"; final SubscriptionDescription subscription1 = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setLockDuration(Duration.ofSeconds(15)) .setDefaultMessageTimeToLive(Duration.ofMinutes(5)) .setMaxDeliveryCount(5) .setAutoDeleteOnIdle(Duration.ofDays(1))); final SubscriptionDescription subscription2 = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setSessionRequired(true) .setLockDuration(Duration.ofSeconds(15)) .setMaxDeliveryCount(5)); final SubscriptionDescription subscription3 = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setSessionRequired(true) .setLockDuration(Duration.ofSeconds(15)) .setMaxDeliveryCount(5)); final List<SubscriptionDescription> expectedDescriptions = Arrays.asList( subscription1, subscription2, subscription3); final SubscriptionDescriptionEntry entry1 = new SubscriptionDescriptionEntry() .setId("https: .setTitle(getResponseTitle(subscriptionName1)) .setPublished(OffsetDateTime.parse("2020-06-22T23:47:53Z")) .setUpdated(OffsetDateTime.parse("2020-06-23T23:47:53Z")) .setLink(new ResponseLink().setRel("self").setHref("Subscriptions/subscription-0?api-version=2021-05")) .setContent(new SubscriptionDescriptionEntryContent() .setType("application/xml") .setSubscriptionDescription(subscription1)); final SubscriptionDescriptionEntry entry2 = new SubscriptionDescriptionEntry() .setId("https: .setTitle(getResponseTitle(subscriptionName2)) .setPublished(OffsetDateTime.parse("2020-06-22T23:47:53Z")) .setUpdated(OffsetDateTime.parse("2020-05-22T23:47:53Z")) .setLink(new ResponseLink().setRel("self").setHref("Subscriptions/subscription-session-0?api-version=2021-05")) .setContent(new SubscriptionDescriptionEntryContent() .setType("application/xml") .setSubscriptionDescription(subscription2)); final SubscriptionDescriptionEntry entry3 = new SubscriptionDescriptionEntry() .setId("https: .setTitle(getResponseTitle(subscriptionName3)) .setPublished(OffsetDateTime.parse("2020-06-22T23:47:54Z")) .setUpdated(OffsetDateTime.parse("2020-04-22T23:47:54Z")) .setLink(new ResponseLink().setRel("self").setHref("Subscriptions/subscription-session-1?api-version=2021-05")) .setContent(new SubscriptionDescriptionEntryContent() .setType("application/xml") .setSubscriptionDescription(subscription3)); final Map<String, String> titleMap = new HashMap<>(); titleMap.put("", "Subscriptions"); titleMap.put("type", "text"); final List<SubscriptionDescriptionEntry> entries = Arrays.asList(entry1, entry2, entry3); final SubscriptionDescriptionFeed expected = new SubscriptionDescriptionFeed() .setId("feed-id") .setTitle(titleMap) .setUpdated(OffsetDateTime.parse("2020-06-30T11:41:32Z")) .setLink(responseLinks) .setEntry(entries); final int expectedNumberOfEntries = 11; final SubscriptionDescriptionFeed actual = serializer.deserialize(contents, SubscriptionDescriptionFeed.class); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getTitle(), actual.getTitle()); assertEquals(expected.getUpdated(), actual.getUpdated()); assertNotNull(actual.getLink()); assertEquals(expected.getLink().size(), actual.getLink().size()); for (int i = 0; i < expected.getLink().size(); i++) { final ResponseLink expectedLink = expected.getLink().get(i); final ResponseLink actualLink = actual.getLink().get(i); assertEquals(expectedLink.getRel(), actualLink.getRel()); assertEquals(expectedLink.getHref(), actualLink.getHref()); } assertNotNull(actual.getEntry()); assertTrue(expected.getEntry().size() < actual.getEntry().size()); assertEquals(expectedNumberOfEntries, actual.getEntry().size()); for (int i = 0; i < expected.getEntry().size(); i++) { final SubscriptionDescriptionEntry expectedEntry = expected.getEntry().get(i); final SubscriptionDescriptionEntry actualEntry = actual.getEntry().get(i); assertEquals(expected.getId(), actual.getId()); assertNotNull(actual.getTitle()); assertResponseTitle(expectedEntry.getTitle(), actualEntry.getTitle()); assertEquals(expectedEntry.getUpdated(), actualEntry.getUpdated()); assertEquals(expectedEntry.getPublished(), actualEntry.getPublished()); final SubscriptionDescription expectedSubscription = expectedDescriptions.get(i); assertSubscriptionEquals(expectedSubscription, EntityStatus.ACTIVE, actualEntry.getContent().getSubscriptionDescription()); } }
.setId("https:
void deserializeSubscriptionDescriptionFeed() throws IOException { final String contents = getContents("SubscriptionDescriptionFeed.xml"); final List<ResponseLink> responseLinks = Collections.singletonList( new ResponseLink().setRel("self") .setHref("https: ); final String topicName = "topic"; final String subscriptionName1 = "subscription-0"; final String subscriptionName2 = "subscription-session-0"; final String subscriptionName3 = "subscription-session-1"; final SubscriptionDescription subscription1 = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setLockDuration(Duration.ofSeconds(15)) .setDefaultMessageTimeToLive(Duration.ofMinutes(5)) .setMaxDeliveryCount(5) .setAutoDeleteOnIdle(Duration.ofDays(1))); final SubscriptionDescription subscription2 = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setSessionRequired(true) .setLockDuration(Duration.ofSeconds(15)) .setMaxDeliveryCount(5)); final SubscriptionDescription subscription3 = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setSessionRequired(true) .setLockDuration(Duration.ofSeconds(15)) .setMaxDeliveryCount(5)); final List<SubscriptionDescription> expectedDescriptions = Arrays.asList( subscription1, subscription2, subscription3); final SubscriptionDescriptionEntry entry1 = new SubscriptionDescriptionEntry() .setId("https: .setTitle(getResponseTitle(subscriptionName1)) .setPublished(OffsetDateTime.parse("2020-06-22T23:47:53Z")) .setUpdated(OffsetDateTime.parse("2020-06-23T23:47:53Z")) .setLink(new ResponseLink().setRel("self").setHref("Subscriptions/subscription-0?api-version=2021-05")) .setContent(new SubscriptionDescriptionEntryContent() .setType("application/xml") .setSubscriptionDescription(subscription1)); final SubscriptionDescriptionEntry entry2 = new SubscriptionDescriptionEntry() .setId("https: .setTitle(getResponseTitle(subscriptionName2)) .setPublished(OffsetDateTime.parse("2020-06-22T23:47:53Z")) .setUpdated(OffsetDateTime.parse("2020-05-22T23:47:53Z")) .setLink(new ResponseLink().setRel("self").setHref("Subscriptions/subscription-session-0?api-version=2021-05")) .setContent(new SubscriptionDescriptionEntryContent() .setType("application/xml") .setSubscriptionDescription(subscription2)); final SubscriptionDescriptionEntry entry3 = new SubscriptionDescriptionEntry() .setId("https: .setTitle(getResponseTitle(subscriptionName3)) .setPublished(OffsetDateTime.parse("2020-06-22T23:47:54Z")) .setUpdated(OffsetDateTime.parse("2020-04-22T23:47:54Z")) .setLink(new ResponseLink().setRel("self").setHref("Subscriptions/subscription-session-1?api-version=2021-05")) .setContent(new SubscriptionDescriptionEntryContent() .setType("application/xml") .setSubscriptionDescription(subscription3)); final Map<String, String> titleMap = new HashMap<>(); titleMap.put("", "Subscriptions"); titleMap.put("type", "text"); final List<SubscriptionDescriptionEntry> entries = Arrays.asList(entry1, entry2, entry3); final SubscriptionDescriptionFeed expected = new SubscriptionDescriptionFeed() .setId("feed-id") .setTitle(titleMap) .setUpdated(OffsetDateTime.parse("2020-06-30T11:41:32Z")) .setLink(responseLinks) .setEntry(entries); final int expectedNumberOfEntries = 11; final SubscriptionDescriptionFeed actual = serializer.deserialize(contents, SubscriptionDescriptionFeed.class); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getTitle(), actual.getTitle()); assertEquals(expected.getUpdated(), actual.getUpdated()); assertNotNull(actual.getLink()); assertEquals(expected.getLink().size(), actual.getLink().size()); for (int i = 0; i < expected.getLink().size(); i++) { final ResponseLink expectedLink = expected.getLink().get(i); final ResponseLink actualLink = actual.getLink().get(i); assertEquals(expectedLink.getRel(), actualLink.getRel()); assertEquals(expectedLink.getHref(), actualLink.getHref()); } assertNotNull(actual.getEntry()); assertTrue(expected.getEntry().size() < actual.getEntry().size()); assertEquals(expectedNumberOfEntries, actual.getEntry().size()); for (int i = 0; i < expected.getEntry().size(); i++) { final SubscriptionDescriptionEntry expectedEntry = expected.getEntry().get(i); final SubscriptionDescriptionEntry actualEntry = actual.getEntry().get(i); assertEquals(expected.getId(), actual.getId()); assertNotNull(actual.getTitle()); assertResponseTitle(expectedEntry.getTitle(), actualEntry.getTitle()); assertEquals(expectedEntry.getUpdated(), actualEntry.getUpdated()); assertEquals(expectedEntry.getPublished(), actualEntry.getPublished()); final SubscriptionDescription expectedSubscription = expectedDescriptions.get(i); assertSubscriptionEquals(expectedSubscription, EntityStatus.ACTIVE, actualEntry.getContent().getSubscriptionDescription()); } }
class ServiceBusManagementSerializerTest { private static final String TITLE_KEY = ""; private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer(); /** * Verify we can deserialize XML request when creating a queue. */ @Test void deserializeCreateQueueDescription() throws IOException { final String contents = getContents("CreateQueueEntry.xml"); final AuthorizationRule rule = new SharedAccessAuthorizationRule("test-name", "fakePrimaryKey", "fakeSecondaryKey", Collections.singletonList(AccessRights.SEND)); final CreateQueueOptions expected = new CreateQueueOptions() .setAutoDeleteOnIdle(null) .setDefaultMessageTimeToLive(null) .setDuplicateDetectionHistoryTimeWindow(null) .setLockDuration(Duration.ofMinutes(10)) .setMaxSizeInMegabytes(1028) .setDuplicateDetectionRequired(false) .setSessionRequired(true) .setDeadLetteringOnMessageExpiration(false) .setMaxDeliveryCount(5) .setBatchedOperationsEnabled(true) .setPartitioningEnabled(false); expected.getAuthorizationRules().add(rule); final QueueDescriptionEntry entry = serializer.deserialize(contents, QueueDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); final QueueDescription actual = entry.getContent().getQueueDescription(); assertQueueEquals(expected, EntityStatus.ACTIVE, actual); final List<AuthorizationRule> actualRules = actual.getAuthorizationRules().stream() .map(TestAuthorizationRule::new) .collect(Collectors.toList()); TestUtils.assertAuthorizationRules(expected.getAuthorizationRules(), actualRules); } /** * Verify we can deserialize XML from a GET queue request. */ @Test void deserializeQueueDescription() throws IOException { final String contents = getContents("QueueDescriptionEntry.xml"); final String queueName = "my-test-queue"; final CreateQueueOptions expected = new CreateQueueOptions() .setLockDuration(Duration.ofMinutes(5)) .setMaxSizeInMegabytes(1024) .setDuplicateDetectionRequired(true) .setSessionRequired(true) .setDefaultMessageTimeToLive(Duration.parse("PT3H20M10S")) .setDeadLetteringOnMessageExpiration(false) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(10)) .setMaxDeliveryCount(10) .setBatchedOperationsEnabled(true) .setAutoDeleteOnIdle(Duration.ofHours(5)) .setPartitioningEnabled(true); final QueueDescriptionEntry entry = serializer.deserialize(contents, QueueDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); assertTitle(queueName, entry.getTitle()); final QueueDescription actual = entry.getContent().getQueueDescription(); assertQueueEquals(expected, EntityStatus.DELETING, actual); } /** * Verify we can deserialize XML from a GET queue request and create convenience model, {@link QueueRuntimeProperties}. */ @Test void deserializeQueueRuntimeProperties() throws IOException { final String contents = getContents("QueueDescriptionEntry.xml"); final OffsetDateTime createdAt = OffsetDateTime.parse("2020-06-05T03:55:07.5Z"); final OffsetDateTime updatedAt = OffsetDateTime.parse("2020-06-05T03:45:07.64Z"); final OffsetDateTime accessedAt = OffsetDateTime.parse("0001-01-01T00:00:00Z"); final int sizeInBytes = 2048; final int messageCount = 23; final MessageCountDetails expectedCount = new MessageCountDetails() .setActiveMessageCount(5) .setDeadLetterMessageCount(3) .setScheduledMessageCount(65) .setTransferMessageCount(10) .setTransferDeadLetterMessageCount(123); final QueueDescriptionEntry entry = serializer.deserialize(contents, QueueDescriptionEntry.class); final QueueProperties properties = EntityHelper.toModel(entry.getContent().getQueueDescription()); final QueueRuntimeProperties actual = new QueueRuntimeProperties(properties); assertEquals(sizeInBytes, actual.getSizeInBytes()); assertEquals(messageCount, actual.getTotalMessageCount()); assertEquals(createdAt, actual.getCreatedAt()); assertEquals(updatedAt, actual.getUpdatedAt()); assertEquals(accessedAt, actual.getAccessedAt()); assertEquals(expectedCount.getActiveMessageCount(), actual.getActiveMessageCount()); assertEquals(expectedCount.getDeadLetterMessageCount(), actual.getDeadLetterMessageCount()); assertEquals(expectedCount.getScheduledMessageCount(), actual.getScheduledMessageCount()); assertEquals(expectedCount.getTransferMessageCount(), actual.getTransferMessageCount()); assertEquals(expectedCount.getTransferDeadLetterMessageCount(), actual.getTransferDeadLetterMessageCount()); } /** * Verify we can deserialize feed XML from a list queues operation that has a paged response. */ @Test void deserializeQueueDescriptionFeedPaged() throws IOException { final String contents = getContents("QueueDescriptionFeed-Paged.xml"); final List<ResponseLink> responseLinks = Arrays.asList( new ResponseLink().setRel("self") .setHref("https: new ResponseLink().setRel("next") .setHref("https: ); final String queueName = "q-0"; final CreateQueueOptions options = new CreateQueueOptions() .setLockDuration(Duration.ofMinutes(10)) .setMaxSizeInMegabytes(102) .setDuplicateDetectionRequired(true) .setSessionRequired(true) .setDefaultMessageTimeToLive(Duration.ofSeconds(10)) .setDeadLetteringOnMessageExpiration(false) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(10)) .setMaxDeliveryCount(10) .setBatchedOperationsEnabled(true) .setAutoDeleteOnIdle(Duration.ofSeconds(5)) .setPartitioningEnabled(true); final QueueDescription queueProperties = EntityHelper.getQueueDescription(options); final QueueDescriptionEntry entry1 = new QueueDescriptionEntry() .setBase("https: .setId("https: .setTitle(getResponseTitle("q-0")) .setPublished(OffsetDateTime.parse("2020-03-05T07:17:04Z")) .setUpdated(OffsetDateTime.parse("2020-01-05T07:17:04Z")) .setAuthor(new ResponseAuthor().setName("sb-java")) .setLink(new ResponseLink().setRel("self").setHref("../q-0?api-version=2021-05")) .setContent(new QueueDescriptionEntryContent().setType("application/xml") .setQueueDescription(queueProperties)); final QueueDescriptionEntry entry2 = new QueueDescriptionEntry() .setBase("https: .setId("https: .setTitle(getResponseTitle("q-1")) .setPublished(OffsetDateTime.parse("2020-06-10T07:16:25Z")) .setUpdated(OffsetDateTime.parse("2020-06-15T07:16:25Z")) .setAuthor(new ResponseAuthor().setName("sb-java2")) .setLink(new ResponseLink().setRel("self").setHref("../q-1?api-version=2021-05")) .setContent(new QueueDescriptionEntryContent().setType("application/xml") .setQueueDescription(queueProperties)); final QueueDescriptionEntry entry3 = new QueueDescriptionEntry() .setBase("https: .setId("https: .setTitle(getResponseTitle("q-2")) .setPublished(OffsetDateTime.parse("2020-06-05T07:17:06Z")) .setUpdated(OffsetDateTime.parse("2020-06-05T07:17:06Z")) .setAuthor(new ResponseAuthor().setName("sb-java3")) .setLink(new ResponseLink().setRel("self").setHref("../q-2?api-version=2021-05")) .setContent(new QueueDescriptionEntryContent().setType("application/xml") .setQueueDescription(queueProperties)); final Map<String, String> titleMap = new HashMap<>(); titleMap.put("", "Queues"); titleMap.put("type", "text"); final List<QueueDescriptionEntry> entries = Arrays.asList(entry1, entry2, entry3); final QueueDescriptionFeed expected = new QueueDescriptionFeed() .setId("feed-id") .setTitle(titleMap) .setUpdated(OffsetDateTime.parse("2020-12-05T07:17:21Z")) .setLink(responseLinks) .setEntry(entries); final QueueDescriptionFeed actual = serializer.deserialize(contents, QueueDescriptionFeed.class); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getTitle(), actual.getTitle()); assertEquals(expected.getUpdated(), actual.getUpdated()); assertNotNull(actual.getLink()); assertEquals(expected.getLink().size(), actual.getLink().size()); for (int i = 0; i < expected.getLink().size(); i++) { final ResponseLink expectedLink = expected.getLink().get(i); final ResponseLink actualLink = actual.getLink().get(i); assertEquals(expectedLink.getRel(), actualLink.getRel()); assertEquals(expectedLink.getHref(), actualLink.getHref()); } assertNotNull(actual.getEntry()); assertEquals(expected.getEntry().size(), actual.getEntry().size()); for (int i = 0; i < expected.getEntry().size(); i++) { final QueueDescriptionEntry expectedEntry = expected.getEntry().get(i); final QueueDescriptionEntry actualEntry = actual.getEntry().get(i); assertEquals(expected.getId(), actual.getId()); assertNotNull(actual.getTitle()); assertResponseTitle(expectedEntry.getTitle(), actualEntry.getTitle()); assertEquals(expectedEntry.getUpdated(), actualEntry.getUpdated()); assertEquals(expectedEntry.getPublished(), actualEntry.getPublished()); assertEquals(expectedEntry.getAuthor().getName(), actualEntry.getAuthor().getName()); assertQueueEquals(options, EntityStatus.ACTIVE, actualEntry.getContent().getQueueDescription()); } } /** * Verify we can deserialize XML from a GET namespace request. */ @Test void deserializeNamespace() throws IOException { final String contents = getContents("NamespaceEntry.xml"); final String name = "ShivangiServiceBus"; final String alias = "MyServiceBusFallback"; final OffsetDateTime createdTime = OffsetDateTime.parse("2020-04-09T08:38:55.807Z"); final OffsetDateTime modifiedTime = OffsetDateTime.parse("2020-06-12T06:34:38.383Z"); final MessagingSku sku = MessagingSku.PREMIUM; final NamespaceType namespaceType = NamespaceType.MESSAGING; final NamespacePropertiesEntry entry = serializer.deserialize(contents, NamespacePropertiesEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); assertTitle(name, entry.getTitle()); final NamespaceProperties actual = entry.getContent().getNamespaceProperties(); assertEquals(name, actual.getName()); assertEquals(alias, actual.getAlias()); assertEquals(createdTime, actual.getCreatedTime()); assertEquals(modifiedTime, actual.getModifiedTime()); assertEquals(sku, actual.getMessagingSku()); assertEquals(namespaceType, actual.getNamespaceType()); } /** * Verify we can deserialize XML from a GET subscription request. */ @Test void deserializeSubscription() throws IOException { final String contents = getContents("SubscriptionDescriptionEntry.xml"); final SubscriptionDescription expected = new SubscriptionDescription() .setLockDuration(Duration.ofSeconds(15)) .setRequiresSession(true) .setDefaultMessageTimeToLive(ServiceBusConstants.MAX_DURATION) .setDeadLetteringOnMessageExpiration(false) .setDeadLetteringOnFilterEvaluationExceptions(true) .setEnableBatchedOperations(true) .setMaxDeliveryCount(5) .setAutoDeleteOnIdle(Duration.ofHours(1).plusMinutes(48)); final SubscriptionDescriptionEntry entry = serializer.deserialize(contents, SubscriptionDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); final SubscriptionDescription actual = entry.getContent().getSubscriptionDescription(); assertSubscriptionEquals(expected, EntityStatus.ACTIVE, actual); } /** * Verify we can deserialize XML from a PUT subscription request. */ @Test void deserializeCreateSubscription() throws IOException { final String contents = getContents("CreateSubscriptionEntry.xml"); final String topicName = "topic"; final String subscriptionName = "sub46850f"; final SubscriptionDescription expected = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setAutoDeleteOnIdle(Duration.parse("P10675199DT2H48M5.477S")) .setDefaultMessageTimeToLive(Duration.parse("P10675199DT2H48M5.477S")) .setSessionRequired(false) .setLockDuration(Duration.ofSeconds(45)) .setMaxDeliveryCount(7)); final SubscriptionDescriptionEntry entry = serializer.deserialize(contents, SubscriptionDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); final SubscriptionDescription actual = entry.getContent().getSubscriptionDescription(); assertSubscriptionEquals(expected, EntityStatus.ACTIVE, actual); } /** * Verify we can deserialize XML from a GET subscription request and create convenience model, {@link * SubscriptionRuntimeProperties}. */ @Test void deserializeSubscriptionRuntimeProperties() throws IOException { final String contents = getContents("SubscriptionDescriptionEntry.xml"); final OffsetDateTime createdAt = OffsetDateTime.parse("2020-06-22T23:47:54.0131447Z"); final OffsetDateTime updatedAt = OffsetDateTime.parse("2020-06-22T23:47:20.0131447Z"); final OffsetDateTime accessedAt = OffsetDateTime.parse("2020-06-22T23:47:54.013Z"); final int messageCount = 13; final MessageCountDetails expectedCount = new MessageCountDetails() .setActiveMessageCount(10) .setDeadLetterMessageCount(50) .setScheduledMessageCount(34) .setTransferMessageCount(11) .setTransferDeadLetterMessageCount(2); final SubscriptionDescriptionEntry entry = serializer.deserialize(contents, SubscriptionDescriptionEntry.class); final SubscriptionRuntimeProperties actual = new SubscriptionRuntimeProperties( EntityHelper.toModel(entry.getContent().getSubscriptionDescription())); assertEquals(messageCount, actual.getTotalMessageCount()); assertEquals(createdAt, actual.getCreatedAt()); assertEquals(updatedAt, actual.getUpdatedAt()); assertEquals(accessedAt, actual.getAccessedAt()); assertEquals(expectedCount.getActiveMessageCount(), actual.getActiveMessageCount()); assertEquals(expectedCount.getDeadLetterMessageCount(), actual.getDeadLetterMessageCount()); assertEquals(expectedCount.getTransferMessageCount(), actual.getTransferMessageCount()); assertEquals(expectedCount.getTransferDeadLetterMessageCount(), actual.getTransferDeadLetterMessageCount()); } /** * Verify we can deserialize feed XML from a list of subscriptions that has a paged response. */ @Test /** * Verify we can deserialize XML from a GET rule. */ @Test void deserializeSqlRule() throws IOException { final String contents = getContents("SqlRuleFilter.xml"); final RuleDescription expectedRule = new RuleDescription() .setName("foo") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:32:20.9387321Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new SqlFilterImpl() .setCompatibilityLevel("20") .setSqlExpression("type = \"TestType\"")); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("sb: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:20Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:34:20Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(expectedRule) .setType("application/xml")); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Verify we can deserialize XML from a GET rule that includes an action. */ @Test void deserializeSqlRuleWithAction() throws IOException { final String contents = getContents("SqlRuleFilterWithAction.xml"); final RuleDescription expectedRule = new RuleDescription() .setName("foo") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:51:24.9967451Z")) .setAction(new SqlRuleActionImpl() .setCompatibilityLevel("20") .setSqlExpression("set FilterTag = 'true'")) .setFilter(new SqlFilterImpl() .setCompatibilityLevel("20") .setSqlExpression("type = \"TestType\"")); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-28T04:51:24Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:54:24Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(expectedRule) .setType("application/xml")); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Verify we can deserialize XML from a GET correlation filter rule that includes an action. */ @Test void deserializeCorrelationFilterRule() throws IOException { final String contents = getContents("CorrelationRuleFilter.xml"); final RuleDescription expectedRule = new RuleDescription() .setName("correlation-test") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:32:50.7697024Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new CorrelationFilterImpl() .setLabel("matching-label")); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("sb: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:50Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:34:50Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(expectedRule) .setType("application/xml")); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Verify we can deserialize XML from a GET rule that includes an action. */ @Test void deserializeRulesFeed() throws IOException { final String contents = getContents("RuleDescriptionFeed.xml"); final RuleDescription defaultRule = new RuleDescription() .setName("$Default") .setCreatedAt(OffsetDateTime.parse("2020-08-12T18:48:00.1005312Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new TrueFilterImpl().setCompatibilityLevel("20").setSqlExpression("1=1")); final RuleDescriptionEntry defaultRuleEntry = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-12T18:48:00Z")) .setUpdated(OffsetDateTime.parse("2020-08-12T18:48:00Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(defaultRule) .setType("application/xml")); final RuleDescription correlation = new RuleDescription() .setName("correl") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:32:50.7697024Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new CorrelationFilterImpl() .setLabel("matching-label")); final RuleDescriptionEntry correlationEntry = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:50Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:32:50Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(correlation) .setType("application/xml")); final RuleDescription sqlRule = new RuleDescription() .setName("foo") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:51:24.9967451Z")) .setAction(new SqlRuleActionImpl() .setCompatibilityLevel("20") .setSqlExpression("set FilterTag = 'true'")) .setFilter(new SqlFilterImpl() .setCompatibilityLevel("20") .setSqlExpression("type = \"TestType\"")); final RuleDescriptionEntry sqlRuleEntry = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:20Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:32:20Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(sqlRule) .setType("application/xml")); final List<RuleDescriptionEntry> expectedEntries = Arrays.asList(defaultRuleEntry, correlationEntry, sqlRuleEntry); final RuleDescriptionFeed expected = new RuleDescriptionFeed() .setEntry(expectedEntries) .setId("https: .setUpdated(OffsetDateTime.parse("2020-08-28T14:59:16Z")); final RuleDescriptionFeed actual = serializer.deserialize(contents, RuleDescriptionFeed.class); assertNotNull(actual); assertEquals(expected.getId(), actual.getId()); final List<RuleDescriptionEntry> actualEntries = actual.getEntry(); assertNotNull(actualEntries); assertEquals(expectedEntries.size(), actualEntries.size()); for (int i = 0; i < expected.getEntry().size(); i++) { final RuleDescriptionEntry expectedRule = expectedEntries.get(i); final RuleDescriptionEntry actualRule = actualEntries.get(i); assertRuleEntryEquals(expectedRule, actualRule); } } @Test void deserializeRuleEntry() throws IOException { final String contents = getContents("CreateRuleEntry.xml"); final RuleDescription description = new RuleDescription() .setName("connies-bar") .setAction(new SqlRuleActionImpl().setSqlExpression("SET Label = 'my-label'")) .setFilter(new TrueFilterImpl().setSqlExpression("1=1")); final RuleDescriptionEntryContent content = new RuleDescriptionEntryContent() .setRuleDescription(description) .setType("application/xml"); final RuleDescriptionEntry expected = new RuleDescriptionEntry().setContent(content); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } @Test void deserializeRuleEntryResponse() throws IOException { final String contents = getContents("CreateRuleEntryResponse.xml"); final RuleDescription description = new RuleDescription() .setName("connies-bar") .setAction(new SqlRuleActionImpl().setSqlExpression("SET Label = 'my-label'").setCompatibilityLevel("20")) .setFilter(new TrueFilterImpl().setSqlExpression("1=1").setCompatibilityLevel("20")) .setCreatedAt(OffsetDateTime.parse("2020-10-05T23:34:21.5963322Z")); final RuleDescriptionEntryContent content = new RuleDescriptionEntryContent() .setRuleDescription(description) .setType("application/xml"); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-10-05T23:31:21Z")) .setUpdated(OffsetDateTime.parse("2020-10-05T23:30:21Z")) .setLink(new ResponseLink() .setRel("self") .setHref("https: .setContent(content); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Given a file name, gets the corresponding resource and its contents as a string. * * @param fileName Name of file to fetch. * * @return Contents of the file. */ private String getContents(String fileName) { final URL resourceUrl = getClass().getClassLoader().getResource("."); assertNotNull(resourceUrl); final File resourceFolder = new File(resourceUrl.getFile(), "xml"); assertTrue(resourceFolder.exists()); final Path path = Paths.get(resourceFolder.getPath(), fileName); try { return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); } catch (IOException e) { fail(String.format("Unable to read file: ' %s'. Error: %s", path.getFileName(), e)); return null; } } private static void assertQueueEquals(CreateQueueOptions expected, EntityStatus expectedStatus, QueueDescription actual) { assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isRequiresDuplicateDetection()); assertEquals(expected.isSessionRequired(), actual.isRequiresSession()); assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.isBatchedOperationsEnabled(), actual.isEnableBatchedOperations()); assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.isPartitioningEnabled(), actual.isEnablePartitioning()); assertEquals(expectedStatus, actual.getStatus()); } private static void assertSubscriptionEquals(SubscriptionDescription expected, EntityStatus expectedStatus, SubscriptionDescription actual) { assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.isDeadLetteringOnFilterEvaluationExceptions(), actual.isDeadLetteringOnFilterEvaluationExceptions()); assertEquals(expected.isRequiresSession(), actual.isRequiresSession()); assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.isEnableBatchedOperations(), actual.isEnableBatchedOperations()); assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expectedStatus, actual.getStatus()); } private static void assertRuleEntryEquals(RuleDescriptionEntry expected, RuleDescriptionEntry actual) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.getId(), actual.getId()); if (expected.getContent() == null) { assertNull(actual.getContent()); return; } assertNotNull(actual.getContent()); assertEquals(expected.getContent().getType(), actual.getContent().getType()); final RuleDescription expectedRule = expected.getContent().getRuleDescription(); final RuleDescription actualRule = actual.getContent().getRuleDescription(); assertNotNull(actualRule); assertRuleEquals(expectedRule, actualRule); } private static void assertRuleEquals(RuleDescription expected, RuleDescription actual) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.getName(), actual.getName()); if (expected.getAction() instanceof EmptyRuleActionImpl) { assertTrue(actual.getAction() instanceof EmptyRuleActionImpl); } else if (expected.getAction() instanceof SqlRuleActionImpl) { assertTrue(actual.getAction() instanceof SqlRuleActionImpl); final SqlRuleActionImpl expectedAction = (SqlRuleActionImpl) expected.getAction(); final SqlRuleActionImpl actualAction = (SqlRuleActionImpl) actual.getAction(); assertEquals(expectedAction.getCompatibilityLevel(), actualAction.getCompatibilityLevel()); assertEquals(expectedAction.getSqlExpression(), actualAction.getSqlExpression()); assertEquals(expectedAction.isRequiresPreprocessing(), actualAction.isRequiresPreprocessing()); assertParameters(expectedAction.getParameters(), actualAction.getParameters()); } if (expected.getFilter() instanceof TrueFilterImpl) { assertTrue(actual.getFilter() instanceof TrueFilterImpl); } else if (expected.getFilter() instanceof FalseFilterImpl) { assertTrue(actual.getFilter() instanceof FalseFilterImpl); } if (expected.getFilter() instanceof SqlFilterImpl) { assertTrue(actual.getFilter() instanceof SqlFilterImpl); final SqlFilterImpl expectedFilter = (SqlFilterImpl) expected.getFilter(); final SqlFilterImpl actualFilter = (SqlFilterImpl) actual.getFilter(); assertEquals(expectedFilter.getCompatibilityLevel(), actualFilter.getCompatibilityLevel()); assertEquals(expectedFilter.getSqlExpression(), actualFilter.getSqlExpression()); assertParameters(expectedFilter.getParameters(), actualFilter.getParameters()); } else if (expected.getFilter() instanceof CorrelationFilterImpl) { assertTrue(actual.getFilter() instanceof CorrelationFilterImpl); final CorrelationFilterImpl expectedFilter = (CorrelationFilterImpl) expected.getFilter(); final CorrelationFilterImpl actualFilter = (CorrelationFilterImpl) actual.getFilter(); assertEquals(expectedFilter.getCorrelationId(), actualFilter.getCorrelationId()); assertEquals(expectedFilter.getMessageId(), actualFilter.getMessageId()); assertEquals(expectedFilter.getTo(), actualFilter.getTo()); assertEquals(expectedFilter.getReplyTo(), actualFilter.getReplyTo()); assertEquals(expectedFilter.getReplyToSessionId(), actualFilter.getReplyToSessionId()); assertEquals(expectedFilter.getSessionId(), actualFilter.getSessionId()); assertEquals(expectedFilter.getContentType(), actualFilter.getContentType()); assertParameters(expectedFilter.getProperties(), actualFilter.getProperties()); } } private static void assertParameters(List<KeyValueImpl> expected, List<KeyValueImpl> actual) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.size(), actual.size()); final Map<String, KeyValueImpl> actualMap = actual.stream() .collect(Collectors.toMap(KeyValueImpl::getKey, Function.identity())); for (KeyValueImpl item : expected) { final KeyValueImpl removed = actualMap.remove(item.getKey()); assertNotNull(removed); assertEquals(item.getValue(), removed.getValue()); } assertTrue(actualMap.isEmpty()); } @SuppressWarnings("unchecked") private static void assertTitle(String expectedTitle, Object responseTitle) { assertTrue(responseTitle instanceof LinkedHashMap); final LinkedHashMap<String, String> map = (LinkedHashMap<String, String>) responseTitle; assertTrue(map.containsKey(TITLE_KEY)); assertEquals(expectedTitle, map.get(TITLE_KEY)); } @SuppressWarnings("unchecked") private static void assertResponseTitle(Object expectedResponseTitle, Object actualResponseTitle) { assertTrue(actualResponseTitle instanceof LinkedHashMap); final LinkedHashMap<String, String> actualMap = (LinkedHashMap<String, String>) actualResponseTitle; assertTrue(actualMap.containsKey(TITLE_KEY)); assertTitle(actualMap.get(TITLE_KEY), expectedResponseTitle); } private static LinkedHashMap<String, String> getResponseTitle(String entityName) { final LinkedHashMap<String, String> map = new LinkedHashMap<>(); map.put("", entityName); map.put("type", "text"); return map; } private static class TestAuthorizationRule implements AuthorizationRule { private final List<AccessRights> accessRights; private final String claimType; private final String claimValue; private final String keyName; private final OffsetDateTime createdAt; private final OffsetDateTime modifiedAt; private final String primaryKey; private final String secondaryKey; TestAuthorizationRule(AuthorizationRuleImpl rule) { this.accessRights = rule.getRights(); this.claimType = rule.getClaimType(); this.claimValue = rule.getClaimValue(); this.createdAt = rule.getCreatedTime(); this.keyName = rule.getKeyName(); this.modifiedAt = rule.getModifiedTime(); this.primaryKey = rule.getPrimaryKey(); this.secondaryKey = rule.getSecondaryKey(); } @Override public List<AccessRights> getAccessRights() { return accessRights; } @Override public String getClaimType() { return claimType; } @Override public String getClaimValue() { return claimValue; } @Override public OffsetDateTime getCreatedAt() { return createdAt; } @Override public String getKeyName() { return keyName; } @Override public OffsetDateTime getModifiedAt() { return modifiedAt; } @Override public String getPrimaryKey() { return primaryKey; } @Override public String getSecondaryKey() { return secondaryKey; } } }
class ServiceBusManagementSerializerTest { private static final String TITLE_KEY = ""; private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer(); /** * Verify we can deserialize XML request when creating a queue. */ @Test void deserializeCreateQueueDescription() throws IOException { final String contents = getContents("CreateQueueEntry.xml"); final AuthorizationRule rule = new SharedAccessAuthorizationRule("test-name", "fakePrimaryKey", "fakeSecondaryKey", Collections.singletonList(AccessRights.SEND)); final CreateQueueOptions expected = new CreateQueueOptions() .setAutoDeleteOnIdle(null) .setDefaultMessageTimeToLive(null) .setDuplicateDetectionHistoryTimeWindow(null) .setLockDuration(Duration.ofMinutes(10)) .setMaxSizeInMegabytes(1028) .setDuplicateDetectionRequired(false) .setSessionRequired(true) .setDeadLetteringOnMessageExpiration(false) .setMaxDeliveryCount(5) .setBatchedOperationsEnabled(true) .setPartitioningEnabled(false); expected.getAuthorizationRules().add(rule); final QueueDescriptionEntry entry = serializer.deserialize(contents, QueueDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); final QueueDescription actual = entry.getContent().getQueueDescription(); assertQueueEquals(expected, EntityStatus.ACTIVE, actual); final List<AuthorizationRule> actualRules = actual.getAuthorizationRules().stream() .map(TestAuthorizationRule::new) .collect(Collectors.toList()); TestUtils.assertAuthorizationRules(expected.getAuthorizationRules(), actualRules); } /** * Verify we can deserialize XML from a GET queue request. */ @Test void deserializeQueueDescription() throws IOException { final String contents = getContents("QueueDescriptionEntry.xml"); final String queueName = "my-test-queue"; final CreateQueueOptions expected = new CreateQueueOptions() .setLockDuration(Duration.ofMinutes(5)) .setMaxSizeInMegabytes(1024) .setDuplicateDetectionRequired(true) .setSessionRequired(true) .setDefaultMessageTimeToLive(Duration.parse("PT3H20M10S")) .setDeadLetteringOnMessageExpiration(false) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(10)) .setMaxDeliveryCount(10) .setBatchedOperationsEnabled(true) .setAutoDeleteOnIdle(Duration.ofHours(5)) .setPartitioningEnabled(true); final QueueDescriptionEntry entry = serializer.deserialize(contents, QueueDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); assertTitle(queueName, entry.getTitle()); final QueueDescription actual = entry.getContent().getQueueDescription(); assertQueueEquals(expected, EntityStatus.DELETING, actual); } /** * Verify we can deserialize XML from a GET queue request and create convenience model, {@link QueueRuntimeProperties}. */ @Test void deserializeQueueRuntimeProperties() throws IOException { final String contents = getContents("QueueDescriptionEntry.xml"); final OffsetDateTime createdAt = OffsetDateTime.parse("2020-06-05T03:55:07.5Z"); final OffsetDateTime updatedAt = OffsetDateTime.parse("2020-06-05T03:45:07.64Z"); final OffsetDateTime accessedAt = OffsetDateTime.parse("0001-01-01T00:00:00Z"); final int sizeInBytes = 2048; final int messageCount = 23; final MessageCountDetails expectedCount = new MessageCountDetails() .setActiveMessageCount(5) .setDeadLetterMessageCount(3) .setScheduledMessageCount(65) .setTransferMessageCount(10) .setTransferDeadLetterMessageCount(123); final QueueDescriptionEntry entry = serializer.deserialize(contents, QueueDescriptionEntry.class); final QueueProperties properties = EntityHelper.toModel(entry.getContent().getQueueDescription()); final QueueRuntimeProperties actual = new QueueRuntimeProperties(properties); assertEquals(sizeInBytes, actual.getSizeInBytes()); assertEquals(messageCount, actual.getTotalMessageCount()); assertEquals(createdAt, actual.getCreatedAt()); assertEquals(updatedAt, actual.getUpdatedAt()); assertEquals(accessedAt, actual.getAccessedAt()); assertEquals(expectedCount.getActiveMessageCount(), actual.getActiveMessageCount()); assertEquals(expectedCount.getDeadLetterMessageCount(), actual.getDeadLetterMessageCount()); assertEquals(expectedCount.getScheduledMessageCount(), actual.getScheduledMessageCount()); assertEquals(expectedCount.getTransferMessageCount(), actual.getTransferMessageCount()); assertEquals(expectedCount.getTransferDeadLetterMessageCount(), actual.getTransferDeadLetterMessageCount()); } /** * Verify we can deserialize feed XML from a list queues operation that has a paged response. */ @Test void deserializeQueueDescriptionFeedPaged() throws IOException { final String contents = getContents("QueueDescriptionFeed-Paged.xml"); final List<ResponseLink> responseLinks = Arrays.asList( new ResponseLink().setRel("self") .setHref("https: new ResponseLink().setRel("next") .setHref("https: ); final String queueName = "q-0"; final CreateQueueOptions options = new CreateQueueOptions() .setLockDuration(Duration.ofMinutes(10)) .setMaxSizeInMegabytes(102) .setDuplicateDetectionRequired(true) .setSessionRequired(true) .setDefaultMessageTimeToLive(Duration.ofSeconds(10)) .setDeadLetteringOnMessageExpiration(false) .setDuplicateDetectionHistoryTimeWindow(Duration.ofMinutes(10)) .setMaxDeliveryCount(10) .setBatchedOperationsEnabled(true) .setAutoDeleteOnIdle(Duration.ofSeconds(5)) .setPartitioningEnabled(true); final QueueDescription queueProperties = EntityHelper.getQueueDescription(options); final QueueDescriptionEntry entry1 = new QueueDescriptionEntry() .setBase("https: .setId("https: .setTitle(getResponseTitle("q-0")) .setPublished(OffsetDateTime.parse("2020-03-05T07:17:04Z")) .setUpdated(OffsetDateTime.parse("2020-01-05T07:17:04Z")) .setAuthor(new ResponseAuthor().setName("sb-java")) .setLink(new ResponseLink().setRel("self").setHref("../q-0?api-version=2021-05")) .setContent(new QueueDescriptionEntryContent().setType("application/xml") .setQueueDescription(queueProperties)); final QueueDescriptionEntry entry2 = new QueueDescriptionEntry() .setBase("https: .setId("https: .setTitle(getResponseTitle("q-1")) .setPublished(OffsetDateTime.parse("2020-06-10T07:16:25Z")) .setUpdated(OffsetDateTime.parse("2020-06-15T07:16:25Z")) .setAuthor(new ResponseAuthor().setName("sb-java2")) .setLink(new ResponseLink().setRel("self").setHref("../q-1?api-version=2021-05")) .setContent(new QueueDescriptionEntryContent().setType("application/xml") .setQueueDescription(queueProperties)); final QueueDescriptionEntry entry3 = new QueueDescriptionEntry() .setBase("https: .setId("https: .setTitle(getResponseTitle("q-2")) .setPublished(OffsetDateTime.parse("2020-06-05T07:17:06Z")) .setUpdated(OffsetDateTime.parse("2020-06-05T07:17:06Z")) .setAuthor(new ResponseAuthor().setName("sb-java3")) .setLink(new ResponseLink().setRel("self").setHref("../q-2?api-version=2021-05")) .setContent(new QueueDescriptionEntryContent().setType("application/xml") .setQueueDescription(queueProperties)); final Map<String, String> titleMap = new HashMap<>(); titleMap.put("", "Queues"); titleMap.put("type", "text"); final List<QueueDescriptionEntry> entries = Arrays.asList(entry1, entry2, entry3); final QueueDescriptionFeed expected = new QueueDescriptionFeed() .setId("feed-id") .setTitle(titleMap) .setUpdated(OffsetDateTime.parse("2020-12-05T07:17:21Z")) .setLink(responseLinks) .setEntry(entries); final QueueDescriptionFeed actual = serializer.deserialize(contents, QueueDescriptionFeed.class); assertEquals(expected.getId(), actual.getId()); assertEquals(expected.getTitle(), actual.getTitle()); assertEquals(expected.getUpdated(), actual.getUpdated()); assertNotNull(actual.getLink()); assertEquals(expected.getLink().size(), actual.getLink().size()); for (int i = 0; i < expected.getLink().size(); i++) { final ResponseLink expectedLink = expected.getLink().get(i); final ResponseLink actualLink = actual.getLink().get(i); assertEquals(expectedLink.getRel(), actualLink.getRel()); assertEquals(expectedLink.getHref(), actualLink.getHref()); } assertNotNull(actual.getEntry()); assertEquals(expected.getEntry().size(), actual.getEntry().size()); for (int i = 0; i < expected.getEntry().size(); i++) { final QueueDescriptionEntry expectedEntry = expected.getEntry().get(i); final QueueDescriptionEntry actualEntry = actual.getEntry().get(i); assertEquals(expected.getId(), actual.getId()); assertNotNull(actual.getTitle()); assertResponseTitle(expectedEntry.getTitle(), actualEntry.getTitle()); assertEquals(expectedEntry.getUpdated(), actualEntry.getUpdated()); assertEquals(expectedEntry.getPublished(), actualEntry.getPublished()); assertEquals(expectedEntry.getAuthor().getName(), actualEntry.getAuthor().getName()); assertQueueEquals(options, EntityStatus.ACTIVE, actualEntry.getContent().getQueueDescription()); } } /** * Verify we can deserialize XML from a GET namespace request. */ @Test void deserializeNamespace() throws IOException { final String contents = getContents("NamespaceEntry.xml"); final String name = "ShivangiServiceBus"; final String alias = "MyServiceBusFallback"; final OffsetDateTime createdTime = OffsetDateTime.parse("2020-04-09T08:38:55.807Z"); final OffsetDateTime modifiedTime = OffsetDateTime.parse("2020-06-12T06:34:38.383Z"); final MessagingSku sku = MessagingSku.PREMIUM; final NamespaceType namespaceType = NamespaceType.MESSAGING; final NamespacePropertiesEntry entry = serializer.deserialize(contents, NamespacePropertiesEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); assertTitle(name, entry.getTitle()); final NamespaceProperties actual = entry.getContent().getNamespaceProperties(); assertEquals(name, actual.getName()); assertEquals(alias, actual.getAlias()); assertEquals(createdTime, actual.getCreatedTime()); assertEquals(modifiedTime, actual.getModifiedTime()); assertEquals(sku, actual.getMessagingSku()); assertEquals(namespaceType, actual.getNamespaceType()); } /** * Verify we can deserialize XML from a GET subscription request. */ @Test void deserializeSubscription() throws IOException { final String contents = getContents("SubscriptionDescriptionEntry.xml"); final SubscriptionDescription expected = new SubscriptionDescription() .setLockDuration(Duration.ofSeconds(15)) .setRequiresSession(true) .setDefaultMessageTimeToLive(ServiceBusConstants.MAX_DURATION) .setDeadLetteringOnMessageExpiration(false) .setDeadLetteringOnFilterEvaluationExceptions(true) .setEnableBatchedOperations(true) .setMaxDeliveryCount(5) .setAutoDeleteOnIdle(Duration.ofHours(1).plusMinutes(48)); final SubscriptionDescriptionEntry entry = serializer.deserialize(contents, SubscriptionDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); final SubscriptionDescription actual = entry.getContent().getSubscriptionDescription(); assertSubscriptionEquals(expected, EntityStatus.ACTIVE, actual); } /** * Verify we can deserialize XML from a PUT subscription request. */ @Test void deserializeCreateSubscription() throws IOException { final String contents = getContents("CreateSubscriptionEntry.xml"); final String topicName = "topic"; final String subscriptionName = "sub46850f"; final SubscriptionDescription expected = EntityHelper.getSubscriptionDescription( new CreateSubscriptionOptions() .setAutoDeleteOnIdle(Duration.parse("P10675199DT2H48M5.477S")) .setDefaultMessageTimeToLive(Duration.parse("P10675199DT2H48M5.477S")) .setSessionRequired(false) .setLockDuration(Duration.ofSeconds(45)) .setMaxDeliveryCount(7)); final SubscriptionDescriptionEntry entry = serializer.deserialize(contents, SubscriptionDescriptionEntry.class); assertNotNull(entry); assertNotNull(entry.getContent()); final SubscriptionDescription actual = entry.getContent().getSubscriptionDescription(); assertSubscriptionEquals(expected, EntityStatus.ACTIVE, actual); } /** * Verify we can deserialize XML from a GET subscription request and create convenience model, {@link * SubscriptionRuntimeProperties}. */ @Test void deserializeSubscriptionRuntimeProperties() throws IOException { final String contents = getContents("SubscriptionDescriptionEntry.xml"); final OffsetDateTime createdAt = OffsetDateTime.parse("2020-06-22T23:47:54.0131447Z"); final OffsetDateTime updatedAt = OffsetDateTime.parse("2020-06-22T23:47:20.0131447Z"); final OffsetDateTime accessedAt = OffsetDateTime.parse("2020-06-22T23:47:54.013Z"); final int messageCount = 13; final MessageCountDetails expectedCount = new MessageCountDetails() .setActiveMessageCount(10) .setDeadLetterMessageCount(50) .setScheduledMessageCount(34) .setTransferMessageCount(11) .setTransferDeadLetterMessageCount(2); final SubscriptionDescriptionEntry entry = serializer.deserialize(contents, SubscriptionDescriptionEntry.class); final SubscriptionRuntimeProperties actual = new SubscriptionRuntimeProperties( EntityHelper.toModel(entry.getContent().getSubscriptionDescription())); assertEquals(messageCount, actual.getTotalMessageCount()); assertEquals(createdAt, actual.getCreatedAt()); assertEquals(updatedAt, actual.getUpdatedAt()); assertEquals(accessedAt, actual.getAccessedAt()); assertEquals(expectedCount.getActiveMessageCount(), actual.getActiveMessageCount()); assertEquals(expectedCount.getDeadLetterMessageCount(), actual.getDeadLetterMessageCount()); assertEquals(expectedCount.getTransferMessageCount(), actual.getTransferMessageCount()); assertEquals(expectedCount.getTransferDeadLetterMessageCount(), actual.getTransferDeadLetterMessageCount()); } /** * Verify we can deserialize feed XML from a list of subscriptions that has a paged response. */ @Test /** * Verify we can deserialize XML from a GET rule. */ @Test void deserializeSqlRule() throws IOException { final String contents = getContents("SqlRuleFilter.xml"); final RuleDescription expectedRule = new RuleDescription() .setName("foo") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:32:20.9387321Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new SqlFilterImpl() .setCompatibilityLevel("20") .setSqlExpression("type = \"TestType\"")); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("sb: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:20Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:34:20Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(expectedRule) .setType("application/xml")); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Verify we can deserialize XML from a GET rule that includes an action. */ @Test void deserializeSqlRuleWithAction() throws IOException { final String contents = getContents("SqlRuleFilterWithAction.xml"); final RuleDescription expectedRule = new RuleDescription() .setName("foo") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:51:24.9967451Z")) .setAction(new SqlRuleActionImpl() .setCompatibilityLevel("20") .setSqlExpression("set FilterTag = 'true'")) .setFilter(new SqlFilterImpl() .setCompatibilityLevel("20") .setSqlExpression("type = \"TestType\"")); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-28T04:51:24Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:54:24Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(expectedRule) .setType("application/xml")); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Verify we can deserialize XML from a GET correlation filter rule that includes an action. */ @Test void deserializeCorrelationFilterRule() throws IOException { final String contents = getContents("CorrelationRuleFilter.xml"); final RuleDescription expectedRule = new RuleDescription() .setName("correlation-test") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:32:50.7697024Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new CorrelationFilterImpl() .setLabel("matching-label")); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("sb: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:50Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:34:50Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(expectedRule) .setType("application/xml")); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Verify we can deserialize XML from a GET rule that includes an action. */ @Test void deserializeRulesFeed() throws IOException { final String contents = getContents("RuleDescriptionFeed.xml"); final RuleDescription defaultRule = new RuleDescription() .setName("$Default") .setCreatedAt(OffsetDateTime.parse("2020-08-12T18:48:00.1005312Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new TrueFilterImpl().setCompatibilityLevel("20").setSqlExpression("1=1")); final RuleDescriptionEntry defaultRuleEntry = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-12T18:48:00Z")) .setUpdated(OffsetDateTime.parse("2020-08-12T18:48:00Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(defaultRule) .setType("application/xml")); final RuleDescription correlation = new RuleDescription() .setName("correl") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:32:50.7697024Z")) .setAction(new EmptyRuleActionImpl()) .setFilter(new CorrelationFilterImpl() .setLabel("matching-label")); final RuleDescriptionEntry correlationEntry = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:50Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:32:50Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(correlation) .setType("application/xml")); final RuleDescription sqlRule = new RuleDescription() .setName("foo") .setCreatedAt(OffsetDateTime.parse("2020-08-28T04:51:24.9967451Z")) .setAction(new SqlRuleActionImpl() .setCompatibilityLevel("20") .setSqlExpression("set FilterTag = 'true'")) .setFilter(new SqlFilterImpl() .setCompatibilityLevel("20") .setSqlExpression("type = \"TestType\"")); final RuleDescriptionEntry sqlRuleEntry = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-08-28T04:32:20Z")) .setUpdated(OffsetDateTime.parse("2020-08-28T04:32:20Z")) .setContent(new RuleDescriptionEntryContent() .setRuleDescription(sqlRule) .setType("application/xml")); final List<RuleDescriptionEntry> expectedEntries = Arrays.asList(defaultRuleEntry, correlationEntry, sqlRuleEntry); final RuleDescriptionFeed expected = new RuleDescriptionFeed() .setEntry(expectedEntries) .setId("https: .setUpdated(OffsetDateTime.parse("2020-08-28T14:59:16Z")); final RuleDescriptionFeed actual = serializer.deserialize(contents, RuleDescriptionFeed.class); assertNotNull(actual); assertEquals(expected.getId(), actual.getId()); final List<RuleDescriptionEntry> actualEntries = actual.getEntry(); assertNotNull(actualEntries); assertEquals(expectedEntries.size(), actualEntries.size()); for (int i = 0; i < expected.getEntry().size(); i++) { final RuleDescriptionEntry expectedRule = expectedEntries.get(i); final RuleDescriptionEntry actualRule = actualEntries.get(i); assertRuleEntryEquals(expectedRule, actualRule); } } @Test void deserializeRuleEntry() throws IOException { final String contents = getContents("CreateRuleEntry.xml"); final RuleDescription description = new RuleDescription() .setName("connies-bar") .setAction(new SqlRuleActionImpl().setSqlExpression("SET Label = 'my-label'")) .setFilter(new TrueFilterImpl().setSqlExpression("1=1")); final RuleDescriptionEntryContent content = new RuleDescriptionEntryContent() .setRuleDescription(description) .setType("application/xml"); final RuleDescriptionEntry expected = new RuleDescriptionEntry().setContent(content); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } @Test void deserializeRuleEntryResponse() throws IOException { final String contents = getContents("CreateRuleEntryResponse.xml"); final RuleDescription description = new RuleDescription() .setName("connies-bar") .setAction(new SqlRuleActionImpl().setSqlExpression("SET Label = 'my-label'").setCompatibilityLevel("20")) .setFilter(new TrueFilterImpl().setSqlExpression("1=1").setCompatibilityLevel("20")) .setCreatedAt(OffsetDateTime.parse("2020-10-05T23:34:21.5963322Z")); final RuleDescriptionEntryContent content = new RuleDescriptionEntryContent() .setRuleDescription(description) .setType("application/xml"); final RuleDescriptionEntry expected = new RuleDescriptionEntry() .setId("https: .setPublished(OffsetDateTime.parse("2020-10-05T23:31:21Z")) .setUpdated(OffsetDateTime.parse("2020-10-05T23:30:21Z")) .setLink(new ResponseLink() .setRel("self") .setHref("https: .setContent(content); final RuleDescriptionEntry actual = serializer.deserialize(contents, RuleDescriptionEntry.class); assertRuleEntryEquals(expected, actual); } /** * Given a file name, gets the corresponding resource and its contents as a string. * * @param fileName Name of file to fetch. * * @return Contents of the file. */ private String getContents(String fileName) { final URL resourceUrl = getClass().getClassLoader().getResource("."); assertNotNull(resourceUrl); final File resourceFolder = new File(resourceUrl.getFile(), "xml"); assertTrue(resourceFolder.exists()); final Path path = Paths.get(resourceFolder.getPath(), fileName); try { return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); } catch (IOException e) { fail(String.format("Unable to read file: ' %s'. Error: %s", path.getFileName(), e)); return null; } } private static void assertQueueEquals(CreateQueueOptions expected, EntityStatus expectedStatus, QueueDescription actual) { assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.isDuplicateDetectionRequired(), actual.isRequiresDuplicateDetection()); assertEquals(expected.isSessionRequired(), actual.isRequiresSession()); assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.isBatchedOperationsEnabled(), actual.isEnableBatchedOperations()); assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.isPartitioningEnabled(), actual.isEnablePartitioning()); assertEquals(expectedStatus, actual.getStatus()); } private static void assertSubscriptionEquals(SubscriptionDescription expected, EntityStatus expectedStatus, SubscriptionDescription actual) { assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.getLockDuration(), actual.getLockDuration()); assertEquals(expected.isDeadLetteringOnFilterEvaluationExceptions(), actual.isDeadLetteringOnFilterEvaluationExceptions()); assertEquals(expected.isRequiresSession(), actual.isRequiresSession()); assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive()); assertEquals(expected.isDeadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration()); assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount()); assertEquals(expected.isEnableBatchedOperations(), actual.isEnableBatchedOperations()); assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expectedStatus, actual.getStatus()); } private static void assertRuleEntryEquals(RuleDescriptionEntry expected, RuleDescriptionEntry actual) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.getId(), actual.getId()); if (expected.getContent() == null) { assertNull(actual.getContent()); return; } assertNotNull(actual.getContent()); assertEquals(expected.getContent().getType(), actual.getContent().getType()); final RuleDescription expectedRule = expected.getContent().getRuleDescription(); final RuleDescription actualRule = actual.getContent().getRuleDescription(); assertNotNull(actualRule); assertRuleEquals(expectedRule, actualRule); } private static void assertRuleEquals(RuleDescription expected, RuleDescription actual) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.getName(), actual.getName()); if (expected.getAction() instanceof EmptyRuleActionImpl) { assertTrue(actual.getAction() instanceof EmptyRuleActionImpl); } else if (expected.getAction() instanceof SqlRuleActionImpl) { assertTrue(actual.getAction() instanceof SqlRuleActionImpl); final SqlRuleActionImpl expectedAction = (SqlRuleActionImpl) expected.getAction(); final SqlRuleActionImpl actualAction = (SqlRuleActionImpl) actual.getAction(); assertEquals(expectedAction.getCompatibilityLevel(), actualAction.getCompatibilityLevel()); assertEquals(expectedAction.getSqlExpression(), actualAction.getSqlExpression()); assertEquals(expectedAction.isRequiresPreprocessing(), actualAction.isRequiresPreprocessing()); assertParameters(expectedAction.getParameters(), actualAction.getParameters()); } if (expected.getFilter() instanceof TrueFilterImpl) { assertTrue(actual.getFilter() instanceof TrueFilterImpl); } else if (expected.getFilter() instanceof FalseFilterImpl) { assertTrue(actual.getFilter() instanceof FalseFilterImpl); } if (expected.getFilter() instanceof SqlFilterImpl) { assertTrue(actual.getFilter() instanceof SqlFilterImpl); final SqlFilterImpl expectedFilter = (SqlFilterImpl) expected.getFilter(); final SqlFilterImpl actualFilter = (SqlFilterImpl) actual.getFilter(); assertEquals(expectedFilter.getCompatibilityLevel(), actualFilter.getCompatibilityLevel()); assertEquals(expectedFilter.getSqlExpression(), actualFilter.getSqlExpression()); assertParameters(expectedFilter.getParameters(), actualFilter.getParameters()); } else if (expected.getFilter() instanceof CorrelationFilterImpl) { assertTrue(actual.getFilter() instanceof CorrelationFilterImpl); final CorrelationFilterImpl expectedFilter = (CorrelationFilterImpl) expected.getFilter(); final CorrelationFilterImpl actualFilter = (CorrelationFilterImpl) actual.getFilter(); assertEquals(expectedFilter.getCorrelationId(), actualFilter.getCorrelationId()); assertEquals(expectedFilter.getMessageId(), actualFilter.getMessageId()); assertEquals(expectedFilter.getTo(), actualFilter.getTo()); assertEquals(expectedFilter.getReplyTo(), actualFilter.getReplyTo()); assertEquals(expectedFilter.getReplyToSessionId(), actualFilter.getReplyToSessionId()); assertEquals(expectedFilter.getSessionId(), actualFilter.getSessionId()); assertEquals(expectedFilter.getContentType(), actualFilter.getContentType()); assertParameters(expectedFilter.getProperties(), actualFilter.getProperties()); } } private static void assertParameters(List<KeyValueImpl> expected, List<KeyValueImpl> actual) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.size(), actual.size()); final Map<String, KeyValueImpl> actualMap = actual.stream() .collect(Collectors.toMap(KeyValueImpl::getKey, Function.identity())); for (KeyValueImpl item : expected) { final KeyValueImpl removed = actualMap.remove(item.getKey()); assertNotNull(removed); assertEquals(item.getValue(), removed.getValue()); } assertTrue(actualMap.isEmpty()); } @SuppressWarnings("unchecked") private static void assertTitle(String expectedTitle, Object responseTitle) { assertTrue(responseTitle instanceof LinkedHashMap); final LinkedHashMap<String, String> map = (LinkedHashMap<String, String>) responseTitle; assertTrue(map.containsKey(TITLE_KEY)); assertEquals(expectedTitle, map.get(TITLE_KEY)); } @SuppressWarnings("unchecked") private static void assertResponseTitle(Object expectedResponseTitle, Object actualResponseTitle) { assertTrue(actualResponseTitle instanceof LinkedHashMap); final LinkedHashMap<String, String> actualMap = (LinkedHashMap<String, String>) actualResponseTitle; assertTrue(actualMap.containsKey(TITLE_KEY)); assertTitle(actualMap.get(TITLE_KEY), expectedResponseTitle); } private static LinkedHashMap<String, String> getResponseTitle(String entityName) { final LinkedHashMap<String, String> map = new LinkedHashMap<>(); map.put("", entityName); map.put("type", "text"); return map; } private static class TestAuthorizationRule implements AuthorizationRule { private final List<AccessRights> accessRights; private final String claimType; private final String claimValue; private final String keyName; private final OffsetDateTime createdAt; private final OffsetDateTime modifiedAt; private final String primaryKey; private final String secondaryKey; TestAuthorizationRule(AuthorizationRuleImpl rule) { this.accessRights = rule.getRights(); this.claimType = rule.getClaimType(); this.claimValue = rule.getClaimValue(); this.createdAt = rule.getCreatedTime(); this.keyName = rule.getKeyName(); this.modifiedAt = rule.getModifiedTime(); this.primaryKey = rule.getPrimaryKey(); this.secondaryKey = rule.getSecondaryKey(); } @Override public List<AccessRights> getAccessRights() { return accessRights; } @Override public String getClaimType() { return claimType; } @Override public String getClaimValue() { return claimValue; } @Override public OffsetDateTime getCreatedAt() { return createdAt; } @Override public String getKeyName() { return keyName; } @Override public OffsetDateTime getModifiedAt() { return modifiedAt; } @Override public String getPrimaryKey() { return primaryKey; } @Override public String getSecondaryKey() { return secondaryKey; } } }
we should try to normalize the preferredRegions before logging it in the ClientTelemetry, otherwise we may have many different values, toLowerCase and trim space, this is the same logic that the internal of the SDK uses as well for normalizing the preferred regions "East US 2" -> "eastus2"
public void serialize(ClientTelemetryInfo telemetry, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { generator.writeStartObject(); generator.writeStringField("timeStamp", telemetry.getTimeStamp()); generator.writeStringField("clientId", telemetry.getClientId()); if (telemetry.getProcessId() != null) { generator.writeStringField("processId", telemetry.getProcessId()); } if (telemetry.getUserAgent() != null) { generator.writeStringField("userAgent", telemetry.getUserAgent()); } generator.writeStringField("connectionMode", telemetry.getConnectionMode().toString()); generator.writeStringField("globalDatabaseAccountName", telemetry.getGlobalDatabaseAccountName()); if (telemetry.getApplicationRegion() != null) { generator.writeStringField("applicationRegion", telemetry.getApplicationRegion()); } if (telemetry.getHostEnvInfo() != null) { generator.writeStringField("hostEnvInfo", telemetry.getHostEnvInfo()); } if (telemetry.getAcceleratedNetworking() != null) { generator.writeStringField("acceleratedNetworking", telemetry.getAcceleratedNetworking().toString()); } if (telemetry.getPreferredRegions() != null && telemetry.getPreferredRegions().size() > 0) { generator.writeStringField("preferredRegions", telemetry.getPreferredRegions().toString()); } generator.writeNumberField("aggregationIntervalInSec", telemetry.getAggregationIntervalInSec()); generator.writeObjectField("systemInfo", telemetry.getSystemInfoMap().keySet()); generator.writeObjectField("cacheRefreshInfo", telemetry.getCacheRefreshInfoMap().keySet()); generator.writeObjectField("operationInfo", telemetry.getOperationInfoMap().keySet()); generator.writeEndObject(); }
telemetry.getPreferredRegions().toString());
public void serialize(ClientTelemetryInfo telemetry, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { generator.writeStartObject(); generator.writeStringField("timeStamp", telemetry.getTimeStamp()); generator.writeStringField("clientId", telemetry.getClientId()); if (telemetry.getProcessId() != null) { generator.writeStringField("processId", telemetry.getProcessId()); } if (telemetry.getUserAgent() != null) { generator.writeStringField("userAgent", telemetry.getUserAgent()); } generator.writeStringField("connectionMode", telemetry.getConnectionMode().toString()); generator.writeStringField("globalDatabaseAccountName", telemetry.getGlobalDatabaseAccountName()); if (telemetry.getApplicationRegion() != null) { generator.writeStringField("applicationRegion", telemetry.getApplicationRegion()); } if (telemetry.getHostEnvInfo() != null) { generator.writeStringField("hostEnvInfo", telemetry.getHostEnvInfo()); } if (telemetry.getAcceleratedNetworking() != null) { generator.writeStringField("acceleratedNetworking", telemetry.getAcceleratedNetworking().toString()); } if (telemetry.getPreferredRegions() != null && telemetry.getPreferredRegions().size() > 0) { generator.writeObjectField("preferredRegions", telemetry.getPreferredRegions()); } generator.writeNumberField("aggregationIntervalInSec", telemetry.getAggregationIntervalInSec()); generator.writeObjectField("systemInfo", telemetry.getSystemInfoMap().keySet()); generator.writeObjectField("cacheRefreshInfo", telemetry.getCacheRefreshInfoMap().keySet()); generator.writeObjectField("operationInfo", telemetry.getOperationInfoMap().keySet()); generator.writeEndObject(); }
class ClientTelemetrySerializer extends StdSerializer<ClientTelemetryInfo> { private static final long serialVersionUID = -2746532297176812860L; ClientTelemetrySerializer() { super(ClientTelemetryInfo.class); } @Override }
class ClientTelemetrySerializer extends StdSerializer<ClientTelemetryInfo> { private static final long serialVersionUID = -2746532297176812860L; ClientTelemetrySerializer() { super(ClientTelemetryInfo.class); } @Override }
We are keeping everything from customer point of view in client telemtry, .NET also doing same , so we should use exact what they passing
public void serialize(ClientTelemetryInfo telemetry, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { generator.writeStartObject(); generator.writeStringField("timeStamp", telemetry.getTimeStamp()); generator.writeStringField("clientId", telemetry.getClientId()); if (telemetry.getProcessId() != null) { generator.writeStringField("processId", telemetry.getProcessId()); } if (telemetry.getUserAgent() != null) { generator.writeStringField("userAgent", telemetry.getUserAgent()); } generator.writeStringField("connectionMode", telemetry.getConnectionMode().toString()); generator.writeStringField("globalDatabaseAccountName", telemetry.getGlobalDatabaseAccountName()); if (telemetry.getApplicationRegion() != null) { generator.writeStringField("applicationRegion", telemetry.getApplicationRegion()); } if (telemetry.getHostEnvInfo() != null) { generator.writeStringField("hostEnvInfo", telemetry.getHostEnvInfo()); } if (telemetry.getAcceleratedNetworking() != null) { generator.writeStringField("acceleratedNetworking", telemetry.getAcceleratedNetworking().toString()); } if (telemetry.getPreferredRegions() != null && telemetry.getPreferredRegions().size() > 0) { generator.writeStringField("preferredRegions", telemetry.getPreferredRegions().toString()); } generator.writeNumberField("aggregationIntervalInSec", telemetry.getAggregationIntervalInSec()); generator.writeObjectField("systemInfo", telemetry.getSystemInfoMap().keySet()); generator.writeObjectField("cacheRefreshInfo", telemetry.getCacheRefreshInfoMap().keySet()); generator.writeObjectField("operationInfo", telemetry.getOperationInfoMap().keySet()); generator.writeEndObject(); }
telemetry.getPreferredRegions().toString());
public void serialize(ClientTelemetryInfo telemetry, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { generator.writeStartObject(); generator.writeStringField("timeStamp", telemetry.getTimeStamp()); generator.writeStringField("clientId", telemetry.getClientId()); if (telemetry.getProcessId() != null) { generator.writeStringField("processId", telemetry.getProcessId()); } if (telemetry.getUserAgent() != null) { generator.writeStringField("userAgent", telemetry.getUserAgent()); } generator.writeStringField("connectionMode", telemetry.getConnectionMode().toString()); generator.writeStringField("globalDatabaseAccountName", telemetry.getGlobalDatabaseAccountName()); if (telemetry.getApplicationRegion() != null) { generator.writeStringField("applicationRegion", telemetry.getApplicationRegion()); } if (telemetry.getHostEnvInfo() != null) { generator.writeStringField("hostEnvInfo", telemetry.getHostEnvInfo()); } if (telemetry.getAcceleratedNetworking() != null) { generator.writeStringField("acceleratedNetworking", telemetry.getAcceleratedNetworking().toString()); } if (telemetry.getPreferredRegions() != null && telemetry.getPreferredRegions().size() > 0) { generator.writeObjectField("preferredRegions", telemetry.getPreferredRegions()); } generator.writeNumberField("aggregationIntervalInSec", telemetry.getAggregationIntervalInSec()); generator.writeObjectField("systemInfo", telemetry.getSystemInfoMap().keySet()); generator.writeObjectField("cacheRefreshInfo", telemetry.getCacheRefreshInfoMap().keySet()); generator.writeObjectField("operationInfo", telemetry.getOperationInfoMap().keySet()); generator.writeEndObject(); }
class ClientTelemetrySerializer extends StdSerializer<ClientTelemetryInfo> { private static final long serialVersionUID = -2746532297176812860L; ClientTelemetrySerializer() { super(ClientTelemetryInfo.class); } @Override }
class ClientTelemetrySerializer extends StdSerializer<ClientTelemetryInfo> { private static final long serialVersionUID = -2746532297176812860L; ClientTelemetrySerializer() { super(ClientTelemetryInfo.class); } @Override }
Temporary disable due to bug https://github.com/Azure/azure-sdk-for-java/issues/25168
public void testSendToUserString() { BinaryData message = BinaryData.fromString("Hello World!"); assertResponse(client.sendToUserWithResponse("test_user", message, new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); assertResponse(client.sendToUserWithResponse("test_user", message, WebPubSubContentType.TEXT_PLAIN, message.getLength(), null, Context.NONE), 202); }
public void testSendToUserString() { BinaryData message = BinaryData.fromString("Hello World!"); assertResponse(client.sendToUserWithResponse("test_user", message, new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); assertResponse(client.sendToUserWithResponse("test_user", message, WebPubSubContentType.TEXT_PLAIN, message.getLength(), null, Context.NONE), 202); }
class WebPubSubServiceClientTests extends TestBase { private static final String DEFAULT_CONNECTION_STRING = "Endpoint=https: private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("WEB_PUB_SUB_CS", DEFAULT_CONNECTION_STRING); private static final String ENDPOINT = Configuration.getGlobalConfiguration() .get("WEB_PUB_SUB_ENDPOINT", "https: private WebPubSubServiceClient client; private WebPubSubServiceAsyncClient asyncClient; @BeforeEach public void setup() { WebPubSubServiceClientBuilder webPubSubServiceClientBuilder = new WebPubSubServiceClientBuilder() .connectionString(CONNECTION_STRING) .httpClient(HttpClient.createDefault()) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { webPubSubServiceClientBuilder.httpClient(interceptorManager.getPlaybackClient()); } else if (getTestMode() == TestMode.RECORD) { webPubSubServiceClientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = webPubSubServiceClientBuilder .buildClient(); this.asyncClient = webPubSubServiceClientBuilder .buildAsyncClient(); } private void assertResponse(Response<?> response, int expectedCode) { assertNotNull(response); assertEquals(expectedCode, response.getStatusCode()); } /***************************************************************************************************************** * Sync Tests - WebPubSubServiceClient ****************************************************************************************************************/ @Test public void assertClientNotNull() { assertNotNull(client); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse( BinaryData.fromString("Hello World - Broadcast test!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse( BinaryData.fromBytes(bytes), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "application/octet-stream")), Context.NONE), 202); } @Test @Test public void testSendToUserBytes() { assertResponse(client.sendToUserWithResponse("test_user", BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "application/octet-stream")), Context.NONE), 202); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testSendToConnectionBytes() { assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "application/octet-stream")), Context.NONE), 202); } @Test public void testSendToConnectionJson() { assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), new RequestOptions() .addRequestCallback(request -> request.getHeaders().set("Content-Type", "application/json")), Context.NONE), 202); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions().addRequestCallback(request -> request.getHeaders().set( "Content-Type", "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions, Context.NONE), 202); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions, Context.NONE), 202); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions, Context.NONE), 202); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions, Context.NONE), 202); } @Test public void testRemoveNonExistentUserFromHub() { Response<Void> removeUserResponse = client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions(), Context.NONE); assertEquals(200, removeUserResponse.getStatusCode()); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() throws ParseException { WebPubSubClientAccessToken token = client.getClientAccessToken(new GetClientAccessTokenOptions()); Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); Assertions.assertTrue(token.getUrl().startsWith("wss: Assertions.assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt = JWTParser.parse(authToken); JWTClaimsSet claimsSet = jwt.getJWTClaimsSet(); Assertions.assertNotNull(claimsSet); Assertions.assertNotNull(claimsSet.getAudience()); Assertions.assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); Assertions.assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); } /***************************************************************************************************************** * Sync Tests - WebPubSubGroup ****************************************************************************************************************/ @Test public void testRemoveNonExistentUserFromGroup() { assertResponse(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions(), Context.NONE), 200); } @Test public void testSendMessageToGroup() { assertResponse(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder webPubSubServiceClientBuilder = new WebPubSubServiceClientBuilder() .endpoint(ENDPOINT) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { webPubSubServiceClientBuilder.httpClient(interceptorManager.getPlaybackClient()) .connectionString(CONNECTION_STRING); } else if (getTestMode() == TestMode.RECORD) { webPubSubServiceClientBuilder.addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { webPubSubServiceClientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } this.client = webPubSubServiceClientBuilder.buildClient(); assertResponse(client.sendToUserWithResponse("test_user", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testCheckPermission() { RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "group_name") .setThrowOnError(false); boolean permission = client.checkPermissionWithResponse(WebPubSubPermission.JOIN_LEAVE_GROUP, "connection_id", requestOptions, Context.NONE).getValue(); Assertions.assertFalse(permission); } }
class WebPubSubServiceClientTests extends TestBase { private static final String DEFAULT_CONNECTION_STRING = "Endpoint=https: private static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() .get("WEB_PUB_SUB_CS", DEFAULT_CONNECTION_STRING); private static final String ENDPOINT = Configuration.getGlobalConfiguration() .get("WEB_PUB_SUB_ENDPOINT", "https: private WebPubSubServiceClient client; private WebPubSubServiceAsyncClient asyncClient; @BeforeEach public void setup() { WebPubSubServiceClientBuilder webPubSubServiceClientBuilder = new WebPubSubServiceClientBuilder() .connectionString(CONNECTION_STRING) .httpClient(HttpClient.createDefault()) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { webPubSubServiceClientBuilder.httpClient(interceptorManager.getPlaybackClient()); } else if (getTestMode() == TestMode.RECORD) { webPubSubServiceClientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } this.client = webPubSubServiceClientBuilder .buildClient(); this.asyncClient = webPubSubServiceClientBuilder .buildAsyncClient(); } private void assertResponse(Response<?> response, int expectedCode) { assertNotNull(response); assertEquals(expectedCode, response.getStatusCode()); } /***************************************************************************************************************** * Sync Tests - WebPubSubServiceClient ****************************************************************************************************************/ @Test public void assertClientNotNull() { assertNotNull(client); } @Test public void testBroadcastString() { assertResponse(client.sendToAllWithResponse( BinaryData.fromString("Hello World - Broadcast test!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testBroadcastBytes() { byte[] bytes = "Hello World - Broadcast test!".getBytes(); assertResponse(client.sendToAllWithResponse( BinaryData.fromBytes(bytes), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "application/octet-stream")), Context.NONE), 202); } @Test @Test public void testSendToUserBytes() { assertResponse(client.sendToUserWithResponse("test_user", BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "application/octet-stream")), Context.NONE), 202); } @Test public void testSendToConnectionString() { assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testSendToConnectionBytes() { assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8)), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "application/octet-stream")), Context.NONE), 202); } @Test public void testSendToConnectionJson() { assertResponse(client.sendToConnectionWithResponse("test_connection", BinaryData.fromString("{\"data\": true}"), new RequestOptions() .addRequestCallback(request -> request.getHeaders().set("Content-Type", "application/json")), Context.NONE), 202); } @Test public void testSendToAllJson() { RequestOptions requestOptions = new RequestOptions().addRequestCallback(request -> request.getHeaders().set( "Content-Type", "application/json")); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"boolvalue\": true}"), requestOptions, Context.NONE), 202); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"stringvalue\": \"testingwebpubsub\"}"), requestOptions, Context.NONE), 202); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"intvalue\": 25}"), requestOptions, Context.NONE), 202); assertResponse(client.sendToAllWithResponse(BinaryData.fromString("{\"floatvalue\": 55.4}"), requestOptions, Context.NONE), 202); } @Test public void testRemoveNonExistentUserFromHub() { Response<Void> removeUserResponse = client.removeUserFromAllGroupsWithResponse("testRemoveNonExistentUserFromHub", new RequestOptions(), Context.NONE); assertEquals(200, removeUserResponse.getStatusCode()); } @Test @DoNotRecord(skipInPlayback = true) public void testGetAuthenticationToken() throws ParseException { WebPubSubClientAccessToken token = client.getClientAccessToken(new GetClientAccessTokenOptions()); Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); Assertions.assertNotNull(token.getUrl()); Assertions.assertTrue(token.getUrl().startsWith("wss: Assertions.assertTrue(token.getUrl().contains(".webpubsub.azure.com/client/hubs/")); String authToken = token.getToken(); JWT jwt = JWTParser.parse(authToken); JWTClaimsSet claimsSet = jwt.getJWTClaimsSet(); Assertions.assertNotNull(claimsSet); Assertions.assertNotNull(claimsSet.getAudience()); Assertions.assertFalse(claimsSet.getAudience().isEmpty()); String aud = claimsSet.getAudience().iterator().next(); Assertions.assertTrue(aud.contains(".webpubsub.azure.com/client/hubs/")); } /***************************************************************************************************************** * Sync Tests - WebPubSubGroup ****************************************************************************************************************/ @Test public void testRemoveNonExistentUserFromGroup() { assertResponse(client.removeUserFromGroupWithResponse("java", "testRemoveNonExistentUserFromGroup", new RequestOptions(), Context.NONE), 200); } @Test public void testSendMessageToGroup() { assertResponse(client.sendToGroupWithResponse("java", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testAadCredential() { WebPubSubServiceClientBuilder webPubSubServiceClientBuilder = new WebPubSubServiceClientBuilder() .endpoint(ENDPOINT) .httpClient(HttpClient.createDefault()) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .hub("test"); if (getTestMode() == TestMode.PLAYBACK) { webPubSubServiceClientBuilder.httpClient(interceptorManager.getPlaybackClient()) .connectionString(CONNECTION_STRING); } else if (getTestMode() == TestMode.RECORD) { webPubSubServiceClientBuilder.addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { webPubSubServiceClientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } this.client = webPubSubServiceClientBuilder.buildClient(); assertResponse(client.sendToUserWithResponse("test_user", BinaryData.fromString("Hello World!"), new RequestOptions().addRequestCallback(request -> request.getHeaders() .set("Content-Type", "text/plain")), Context.NONE), 202); } @Test public void testCheckPermission() { RequestOptions requestOptions = new RequestOptions() .addQueryParam("targetName", "group_name") .setThrowOnError(false); boolean permission = client.checkPermissionWithResponse(WebPubSubPermission.JOIN_LEAVE_GROUP, "connection_id", requestOptions, Context.NONE).getValue(); Assertions.assertFalse(permission); } }
Couldn't we avoid creating the temporary stack if we moved the merge operation into the `Context` class itself?
public static Context mergeContexts(Context into, Context from) { Objects.requireNonNull(into, "'into' cannot be null."); Objects.requireNonNull(from, "'from' cannot be null."); Stack<Context> fromContextStack = from.getValueStack(); Context returnContext = into; while (!fromContextStack.empty()) { Context toAdd = fromContextStack.pop(); returnContext = returnContext.addData(toAdd.getKey(), toAdd.getValue()); } return returnContext; }
}
public static Context mergeContexts(Context into, Context from) { Objects.requireNonNull(into, "'into' cannot be null."); Objects.requireNonNull(from, "'from' cannot be null."); Context[] contextChain = from.getContextChain(); Context returnContext = into; for (Context toAdd : contextChain) { if (toAdd != null) { returnContext = returnContext.addData(toAdd.getKey(), toAdd.getValue()); } } return returnContext; }
class from an array of Objects. * * @param args Array of objects to search through to find the first instance of the given `clazz` type. * @param clazz The type trying to be found. * @param <T> Generic type * @return The first object of the desired type, otherwise null. */ public static <T> T findFirstOfType(Object[] args, Class<T> clazz) { if (isNullOrEmpty(args)) { return null; } for (Object arg : args) { if (clazz.isInstance(arg)) { return clazz.cast(arg); } } return null; }
class from an array of Objects. * * @param args Array of objects to search through to find the first instance of the given `clazz` type. * @param clazz The type trying to be found. * @param <T> Generic type * @return The first object of the desired type, otherwise null. */ public static <T> T findFirstOfType(Object[] args, Class<T> clazz) { if (isNullOrEmpty(args)) { return null; } for (Object arg : args) { if (clazz.isInstance(arg)) { return clazz.cast(arg); } } return null; }
Possibly, the issue is that Context is represented in a single-direction linked list with the newest Context first but when merging the oldest should be the first one merged. An additional optimization that could be done is having Context know how many Contexts are in the chain and using an array to create the list of contexts needing to be merged.
public static Context mergeContexts(Context into, Context from) { Objects.requireNonNull(into, "'into' cannot be null."); Objects.requireNonNull(from, "'from' cannot be null."); Stack<Context> fromContextStack = from.getValueStack(); Context returnContext = into; while (!fromContextStack.empty()) { Context toAdd = fromContextStack.pop(); returnContext = returnContext.addData(toAdd.getKey(), toAdd.getValue()); } return returnContext; }
}
public static Context mergeContexts(Context into, Context from) { Objects.requireNonNull(into, "'into' cannot be null."); Objects.requireNonNull(from, "'from' cannot be null."); Context[] contextChain = from.getContextChain(); Context returnContext = into; for (Context toAdd : contextChain) { if (toAdd != null) { returnContext = returnContext.addData(toAdd.getKey(), toAdd.getValue()); } } return returnContext; }
class from an array of Objects. * * @param args Array of objects to search through to find the first instance of the given `clazz` type. * @param clazz The type trying to be found. * @param <T> Generic type * @return The first object of the desired type, otherwise null. */ public static <T> T findFirstOfType(Object[] args, Class<T> clazz) { if (isNullOrEmpty(args)) { return null; } for (Object arg : args) { if (clazz.isInstance(arg)) { return clazz.cast(arg); } } return null; }
class from an array of Objects. * * @param args Array of objects to search through to find the first instance of the given `clazz` type. * @param clazz The type trying to be found. * @param <T> Generic type * @return The first object of the desired type, otherwise null. */ public static <T> T findFirstOfType(Object[] args, Class<T> clazz) { if (isNullOrEmpty(args)) { return null; } for (Object arg : args) { if (clazz.isInstance(arg)) { return clazz.cast(arg); } } return null; }
Nice internal commentary!
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
public Object invoke(Object proxy, final Method method, Object[] args) { validateResumeOperationIsNotPresent(method); try { final SwaggerMethodParser methodParser = getMethodParser(method); final HttpRequest request = createHttpRequest(methodParser, args); Context context = methodParser.setContext(args); RequestOptions options = methodParser.setRequestOptions(args); context = mergeRequestOptionsContext(context, options); context = context.addData("caller-method", methodParser.getFullyQualifiedMethodName()) .addData("azure-eagerly-read-response", shouldEagerlyReadResponse(methodParser.getReturnType())); context = startTracingSpan(method, context); if (options != null) { options.getRequestCallback().accept(request); } if (request.getBody() != null) { request.setBody(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); 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 ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less than the expected %d bytes."; private static final String MUST_IMPLEMENT_PAGE_ERROR = "Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class; private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * 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.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * 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 @SuppressWarnings("deprecation") void validateResumeOperationIsNotPresent(Method method) { if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } static Context mergeRequestOptionsContext(Context context, RequestOptions options) { if (options == null) { return context; } Context optionsContext = options.getContext(); if (optionsContext != null && optionsContext != Context.NONE) { for (Map.Entry<Object, Object> kvp : optionsContext.getValues().entrySet()) { context = context.addData(kvp.getKey(), kvp.getValue()); } } return context; } static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } final long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[1]; return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> { if (buffer == null) { return; } if (buffer == VALIDATION_BUFFER) { if (expectedLength != currentTotalLength[0]) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_SMALL, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } else { sink.complete(); } return; } currentTotalLength[0] += buffer.remaining(); if (currentTotalLength[0] > expectedLength) { sink.error(new UnexpectedLengthException(String.format(BODY_TOO_LARGE, currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); return; } sink.next(buffer); }); }); } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { if (!TracerProxy.isTracingEnabled()) { return context; } if ((boolean) context.getData(Tracer.DISABLE_TRACING_KEY).orElse(false)) { return context; } String spanName = interfaceParser.getServiceName() + "." + method.getName(); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { final String path = methodParser.setPath(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); final UrlBuilder urlBuilder; if (pathUrlBuilder.getScheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); methodParser.setSchemeAndHost(args, urlBuilder); if (path != null && !path.isEmpty() && !"/".equals(path)) { String hostPath = urlBuilder.getPath(); if (hostPath == null || hostPath.isEmpty() || "/".equals(hostPath) || path.contains(": urlBuilder.setPath(path); } else { if (path.startsWith("/")) { urlBuilder.setPath(hostPath + path); } else { urlBuilder.setPath(hostPath + "/" + path); } } } } methodParser.setEncodedQueryParameters(args, urlBuilder); final URL url = urlBuilder.toUrl(); final HttpRequest request = configRequest(new HttpRequest(methodParser.getHttpMethod(), url), methodParser, args); HttpHeaders httpHeaders = request.getHeaders(); methodParser.setHeaders(args, httpHeaders); return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(final HttpRequest request, final SwaggerMethodParser methodParser, final Object[] args) throws IOException { final Object bodyContentObject = methodParser.setBody(args); if (bodyContentObject == null) { request.getHeaders().set("Content-Length", "0"); } else { String contentType = methodParser.getBodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.getHeaders().set("Content-Type", contentType); if (bodyContentObject instanceof BinaryData) { BinaryData binaryData = (BinaryData) bodyContentObject; if (binaryData.getLength() != null) { request.setHeader("Content-Length", binaryData.getLength().toString()); } request.setBody(binaryData.toFluxByteBuffer()); return request; } boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (final String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.JSON, stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } else if (FluxUtil.isFluxByteBuffer(methodParser.getBodyJavaType())) { request.setBody((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.setBody((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.setBody(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.setBody(Flux.just((ByteBuffer) bodyContentObject)); } else { ByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(); serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.getHeaders()), stream); request.setHeader("Content-Length", String.valueOf(stream.size())); request.setBody(Flux.defer(() -> Flux.just(ByteBuffer.wrap(stream.toByteArray(), 0, stream.size())))); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(final Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, options)); } private static Exception instantiateUnexpectedException(final UnexpectedExceptionInformation exception, final HttpResponse httpResponse, final byte[] responseContent, final Object responseDecodedContent) { final int responseStatusCode = httpResponse.getStatusCode(); final String contentType = httpResponse.getHeaderValue("Content-Type"); final String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.getHeaderValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent == null || responseContent.length == 0 ? "(empty body)" : "\"" + new String(responseContent, StandardCharsets.UTF_8) + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.getExceptionType() .getConstructor(String.class, HttpResponse.class, exception.getExceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.getExceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status * code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface method that initiated * the HTTP request. * @return An async-version of the provided decodedResponse. */ private Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, RequestOptions options) { final int responseStatusCode = decodedResponse.getSourceResponse().getStatusCode(); if (methodParser.isExpectedResponseStatusCode(responseStatusCode) || (options != null && options.getErrorOptions().contains(ErrorOptions.NO_THROW))) { return Mono.just(decodedResponse); } return decodedResponse.getSourceResponse().getBodyAsByteArray() .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), null, null)); })) .flatMap(responseBytes -> decodedResponse.getDecodedBody(responseBytes) .switchIfEmpty(Mono.defer(() -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, null)); })) .flatMap(decodedBody -> { return Mono.error(instantiateUnexpectedException( methodParser.getUnexpectedException(responseStatusCode), decodedResponse.getSourceResponse(), responseBytes, decodedBody)); })); } private Mono<?> handleRestResponseReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { return response.getSourceResponse().getBody().ignoreElements() .then(createResponse(response, entityType, null)); } else { return handleBodyReturnType(response, methodParser, bodyType) .flatMap(bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> createResponse(response, entityType, null))); } } else { return handleBodyReturnType(response, methodParser, entityType); } } @SuppressWarnings("unchecked") private Mono<Response<?>> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } final Class<? extends Response<?>> clsFinal = cls; return Mono.just(RESPONSE_CONSTRUCTORS_CACHE.get(clsFinal)) .switchIfEmpty(Mono.defer(() -> Mono.error(new RuntimeException("Cannot find suitable constructor for class " + clsFinal)))) .flatMap(ctr -> RESPONSE_CONSTRUCTORS_CACHE.invoke(ctr, response, bodyAsObject)); } private Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.getSourceResponse().getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf( entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.getSourceResponse().getBodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync .mapNotNull(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { asyncResult = BinaryData.fromFlux(response.getSourceResponse().getBody()); } else { asyncResult = response.getDecodedBody((byte[]) null); } return asyncResult; } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ private Object handleRestReturnType(final Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, final Context context, final RequestOptions options) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser, options) .doOnEach(RestProxy::endTracingSpan) .contextWrite(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.getSourceResponse().getBody()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (!TracerProxy.isTracingEnabled()) { return; } if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } ContextView context = signal.getContextView(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); boolean disableTracing = Boolean.TRUE.equals(context.getOrDefault(Tracer.DISABLE_TRACING_KEY, false)); if (!tracingContext.isPresent() || disableTracing) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.getSourceResponse().getStatusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.getResponse().getStatusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ private static HttpPipeline createDefaultPipeline() { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * 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, createDefaultPipeline(), 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, 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 = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
We should do a similar validation for Storage too to ensure only one of RetryOptions and RequestRetryOptions is set as we do in other builders for policy and options.
public BlobServiceClientBuilder retryOptions(RetryOptions retryOptions) { Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); return this.retryOptions(RequestRetryOptions.fromRetryOptions(retryOptions, null, null)); }
return this.retryOptions(RequestRetryOptions.fromRetryOptions(retryOptions, null, null));
public BlobServiceClientBuilder retryOptions(RetryOptions retryOptions) { this.coreRetryOptions = retryOptions; return this; }
class BlobServiceClientBuilder implements TokenCredentialTrait<BlobServiceClientBuilder>, ConnectionStringTrait<BlobServiceClientBuilder>, AzureNamedKeyCredentialTrait<BlobServiceClientBuilder>, AzureSasCredentialTrait<BlobServiceClientBuilder>, HttpTrait<BlobServiceClientBuilder>, ConfigurationTrait<BlobServiceClientBuilder> { private final ClientLogger logger = new ClientLogger(BlobServiceClientBuilder.class); private String endpoint; private String accountName; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; private BlobContainerEncryptionScope blobContainerEncryptionScope; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions = new RequestRetryOptions(); private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private BlobServiceVersion version; /** * Creates a builder instance that is able to configure and construct {@link BlobServiceClient BlobServiceClients} * and {@link BlobServiceAsyncClient BlobServiceAsyncClients}. */ public BlobServiceClientBuilder() { logOptions = getDefaultHttpLogOptions(); } /** * @return a {@link BlobServiceClient} created from the configurations in this builder. * @throws IllegalArgumentException If no credentials are provided. * @throws IllegalStateException If multiple credentials have been specified. */ public BlobServiceClient buildClient() { return new BlobServiceClient(buildAsyncClient()); } /** * @return a {@link BlobServiceAsyncClient} created from the configurations in this builder. * @throws IllegalArgumentException If no credentials are provided. * @throws IllegalStateException If multiple credentials have been specified. */ public BlobServiceAsyncClient buildAsyncClient() { BuilderHelper.httpsValidation(customerProvidedKey, "customer provided key", endpoint, logger); boolean anonymousAccess = false; if (Objects.nonNull(customerProvidedKey) && Objects.nonNull(encryptionScope)) { throw logger.logExceptionAsError(new IllegalArgumentException("Customer provided key and encryption " + "scope cannot both be set")); } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, endpoint, retryOptions, logOptions, clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger); boolean foundCredential = false; for (int i = 0; i < pipeline.getPolicyCount(); i++) { if (pipeline.getPolicy(i) instanceof StorageSharedKeyCredentialPolicy) { foundCredential = true; break; } if (pipeline.getPolicy(i) instanceof BearerTokenAuthenticationPolicy) { foundCredential = true; break; } if (pipeline.getPolicy(i) instanceof AzureSasCredentialPolicy) { foundCredential = true; break; } } anonymousAccess = !foundCredential; return new BlobServiceAsyncClient(pipeline, endpoint, serviceVersion, accountName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope, anonymousAccess); } /** * Sets the blob service endpoint, additionally parses it for information (SAS token) * * @param endpoint URL of the service * @return the updated BlobServiceClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ public BlobServiceClientBuilder endpoint(String endpoint) { try { BlobUrlParts parts = BlobUrlParts.parse(new URL(endpoint)); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw logger.logExceptionAsError( new IllegalArgumentException("The Azure Storage endpoint url is malformed.")); } return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey Customer provided key containing the encryption key information. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Sets the {@link BlobContainerEncryptionScope encryption scope} that is used to determine how blob contents are * encrypted on the server. * * @param blobContainerEncryptionScope Encryption scope containing the encryption key information. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder blobContainerEncryptionScope( BlobContainerEncryptionScope blobContainerEncryptionScope) { this.blobContainerEncryptionScope = blobContainerEncryptionScope; return this; } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public BlobServiceClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public BlobServiceClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. * * @param credential {@link TokenCredential}. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public BlobServiceClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public BlobServiceClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public BlobServiceClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated BlobServiceClientBuilder * @throws IllegalArgumentException If {@code connectionString} in invalid. * @throws NullPointerException If {@code connectionString} is {@code null}. */ @Override public BlobServiceClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw logger .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the {@link HttpClient} to use for sending a receiving requests to and from the service. * * @param httpClient HttpClient to use for requests. * @return the updated BlobServiceClientBuilder object */ @Override public BlobServiceClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { logger.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If * the method is called multiple times, all policies will be added and their order preserved. * * @param pipelinePolicy a pipeline policy * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public BlobServiceClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public BlobServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ @Override public BlobServiceClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * @param retryOptions {@link RequestRetryOptions}. * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code retryOptions} is {@code null}. */ public BlobServiceClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); return this; } /** * Sets the request retry options for all the requests made through the client. * * Consider using {@link * * @param retryOptions {@link RetryOptions}. * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code retryOptions} is {@code null}. */ @Override /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public BlobServiceClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * * @param httpPipeline HttpPipeline to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ @Override public BlobServiceClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the {@link BlobServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } }
class BlobServiceClientBuilder implements TokenCredentialTrait<BlobServiceClientBuilder>, ConnectionStringTrait<BlobServiceClientBuilder>, AzureNamedKeyCredentialTrait<BlobServiceClientBuilder>, AzureSasCredentialTrait<BlobServiceClientBuilder>, HttpTrait<BlobServiceClientBuilder>, ConfigurationTrait<BlobServiceClientBuilder>, EndpointTrait<BlobServiceClientBuilder> { private final ClientLogger logger = new ClientLogger(BlobServiceClientBuilder.class); private String endpoint; private String accountName; private CpkInfo customerProvidedKey; private EncryptionScope encryptionScope; private BlobContainerEncryptionScope blobContainerEncryptionScope; private StorageSharedKeyCredential storageSharedKeyCredential; private TokenCredential tokenCredential; private AzureSasCredential azureSasCredential; private String sasToken; private HttpClient httpClient; private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private HttpLogOptions logOptions; private RequestRetryOptions retryOptions; private RetryOptions coreRetryOptions; private HttpPipeline httpPipeline; private ClientOptions clientOptions = new ClientOptions(); private Configuration configuration; private BlobServiceVersion version; /** * Creates a builder instance that is able to configure and construct {@link BlobServiceClient BlobServiceClients} * and {@link BlobServiceAsyncClient BlobServiceAsyncClients}. */ public BlobServiceClientBuilder() { logOptions = getDefaultHttpLogOptions(); } /** * @return a {@link BlobServiceClient} created from the configurations in this builder. * @throws IllegalArgumentException If no credentials are provided. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public BlobServiceClient buildClient() { return new BlobServiceClient(buildAsyncClient()); } /** * @return a {@link BlobServiceAsyncClient} created from the configurations in this builder. * @throws IllegalArgumentException If no credentials are provided. * @throws IllegalStateException If multiple credentials have been specified. * @throws IllegalStateException If both {@link * and {@link */ public BlobServiceAsyncClient buildAsyncClient() { BuilderHelper.httpsValidation(customerProvidedKey, "customer provided key", endpoint, logger); boolean anonymousAccess = false; if (Objects.nonNull(customerProvidedKey) && Objects.nonNull(encryptionScope)) { throw logger.logExceptionAsError(new IllegalArgumentException("Customer provided key and encryption " + "scope cannot both be set")); } BlobServiceVersion serviceVersion = version != null ? version : BlobServiceVersion.getLatest(); HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline( storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, endpoint, retryOptions, coreRetryOptions, logOptions, clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger); boolean foundCredential = false; for (int i = 0; i < pipeline.getPolicyCount(); i++) { if (pipeline.getPolicy(i) instanceof StorageSharedKeyCredentialPolicy) { foundCredential = true; break; } if (pipeline.getPolicy(i) instanceof BearerTokenAuthenticationPolicy) { foundCredential = true; break; } if (pipeline.getPolicy(i) instanceof AzureSasCredentialPolicy) { foundCredential = true; break; } } anonymousAccess = !foundCredential; return new BlobServiceAsyncClient(pipeline, endpoint, serviceVersion, accountName, customerProvidedKey, encryptionScope, blobContainerEncryptionScope, anonymousAccess); } /** * Sets the blob service endpoint, additionally parses it for information (SAS token) * * @param endpoint URL of the service * @return the updated BlobServiceClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public BlobServiceClientBuilder endpoint(String endpoint) { try { BlobUrlParts parts = BlobUrlParts.parse(new URL(endpoint)); this.accountName = parts.getAccountName(); this.endpoint = BuilderHelper.getEndpoint(parts); String sasToken = parts.getCommonSasQueryParameters().encode(); if (!CoreUtils.isNullOrEmpty(sasToken)) { this.sasToken(sasToken); } } catch (MalformedURLException ex) { throw logger.logExceptionAsError( new IllegalArgumentException("The Azure Storage endpoint url is malformed.")); } return this; } /** * Sets the {@link CustomerProvidedKey customer provided key} that is used to encrypt blob contents on the server. * * @param customerProvidedKey Customer provided key containing the encryption key information. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder customerProvidedKey(CustomerProvidedKey customerProvidedKey) { if (customerProvidedKey == null) { this.customerProvidedKey = null; } else { this.customerProvidedKey = new CpkInfo() .setEncryptionKey(customerProvidedKey.getKey()) .setEncryptionKeySha256(customerProvidedKey.getKeySha256()) .setEncryptionAlgorithm(customerProvidedKey.getEncryptionAlgorithm()); } return this; } /** * Sets the {@code encryption scope} that is used to encrypt blob contents on the server. * * @param encryptionScope Encryption scope containing the encryption key information. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder encryptionScope(String encryptionScope) { if (encryptionScope == null) { this.encryptionScope = null; } else { this.encryptionScope = new EncryptionScope().setEncryptionScope(encryptionScope); } return this; } /** * Sets the {@link BlobContainerEncryptionScope encryption scope} that is used to determine how blob contents are * encrypted on the server. * * @param blobContainerEncryptionScope Encryption scope containing the encryption key information. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder blobContainerEncryptionScope( BlobContainerEncryptionScope blobContainerEncryptionScope) { this.blobContainerEncryptionScope = blobContainerEncryptionScope; return this; } /** * Sets the {@link StorageSharedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link StorageSharedKeyCredential}. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ public BlobServiceClientBuilder credential(StorageSharedKeyCredential credential) { this.storageSharedKeyCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.tokenCredential = null; this.sasToken = null; return this; } /** * Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service. * * @param credential {@link AzureNamedKeyCredential}. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public BlobServiceClientBuilder credential(AzureNamedKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); return credential(StorageSharedKeyCredential.fromAzureNamedKeyCredential(credential)); } /** * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java * <a href="https: * documentation for more details on proper usage of the {@link TokenCredential} type. * * @param credential {@link TokenCredential} used to authorize requests sent to the service. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public BlobServiceClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); this.storageSharedKeyCredential = null; this.sasToken = null; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. This string should only be the query parameters * (with or without a leading '?') and not a full url. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public BlobServiceClientBuilder sasToken(String sasToken) { this.sasToken = Objects.requireNonNull(sasToken, "'sasToken' cannot be null."); this.storageSharedKeyCredential = null; this.tokenCredential = null; return this; } /** * Sets the {@link AzureSasCredential} used to authorize requests sent to the service. * * @param credential {@link AzureSasCredential} used to authorize requests sent to the service. * @return the updated BlobServiceClientBuilder * @throws NullPointerException If {@code credential} is {@code null}. */ @Override public BlobServiceClientBuilder credential(AzureSasCredential credential) { this.azureSasCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } /** * Sets the connection string to connect to the service. * * @param connectionString Connection string of the storage account. * @return the updated BlobServiceClientBuilder * @throws IllegalArgumentException If {@code connectionString} in invalid. * @throws NullPointerException If {@code connectionString} is {@code null}. */ @Override public BlobServiceClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger); StorageEndpoint endpoint = storageConnectionString.getBlobEndpoint(); if (endpoint == null || endpoint.getPrimaryUri() == null) { throw logger .logExceptionAsError(new IllegalArgumentException( "connectionString missing required settings to derive blob service endpoint.")); } this.endpoint(endpoint.getPrimaryUri()); if (storageConnectionString.getAccountName() != null) { this.accountName = storageConnectionString.getAccountName(); } StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings(); if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) { this.credential(new StorageSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param httpClient The {@link HttpClient} to use for requests. * @return the updated BlobServiceClientBuilder object */ @Override public BlobServiceClientBuilder httpClient(HttpClient httpClient) { if (this.httpClient != null && httpClient == null) { logger.info("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = httpClient; return this; } /** * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param pipelinePolicy A {@link HttpPipelinePolicy pipeline policy}. * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code pipelinePolicy} is {@code null}. */ @Override public BlobServiceClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"); if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(pipelinePolicy); } else { perRetryPolicies.add(pipelinePolicy); } return this; } /** * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to * and from the service. * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code logOptions} is {@code null}. */ @Override public BlobServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Gets the default Storage allowlist log headers and query parameters. * * @return the default http log options. */ public static HttpLogOptions getDefaultHttpLogOptions() { return BuilderHelper.getDefaultHttpLogOptions(); } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated BlobServiceClientBuilder object */ @Override public BlobServiceClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the request retry options for all the requests made through the client. * * Setting this is mutually exclusive with using {@link * * @param retryOptions {@link RequestRetryOptions}. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the {@link RetryOptions} for all the requests made through the client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * Setting this is mutually exclusive with using {@link * Consider using {@link * * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. * @return the updated BlobServiceClientBuilder object */ @Override /** * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is * recommended that this method be called with an instance of the {@link HttpClientOptions} * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait * interface. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * * @param clientOptions A configured instance of {@link HttpClientOptions}. * @see HttpClientOptions * @return the updated BlobServiceClientBuilder object * @throws NullPointerException If {@code clientOptions} is {@code null}. */ @Override public BlobServiceClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the {@link HttpPipeline} to use for the service client. * * <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the * documentation of types that implement this trait to understand the full set of implications.</p> * <p> * The {@link * * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. * @return the updated BlobServiceClientBuilder object */ @Override public BlobServiceClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the {@link BlobServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link BlobServiceVersion} of the service to be used when making requests. * @return the updated BlobServiceClientBuilder object */ public BlobServiceClientBuilder serviceVersion(BlobServiceVersion version) { this.version = version; return this; } }
I assume these two properties are not relevant to resource manager?
void testAzureProfileWithAzureChina() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, AzureResourceManagerExt::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id", "spring.cloud.azure.profile.cloud=AZURE_CHINA" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE_CHINA.getActiveDirectoryEndpoint()); }); }
Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(),
void testAzureProfileWithAzureChina() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, TestAzureResourceManager::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id", "spring.cloud.azure.profile.cloud=AZURE_CHINA" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE_CHINA.getActiveDirectoryEndpoint()); }); }
class AzureResourceManagerAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureResourceManagerAutoConfiguration.class)); @Test void testAzureResourceManagerDisabled() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=false") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithoutTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=true") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.profile.tenant-id=test-tenant") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void testWithoutAzureResourceManagerClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceManager.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testWithoutAzureResourceMetadataClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceMetadata.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testAzureProfileWithAzureDefault() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, AzureResourceManagerExt::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE.getActiveDirectoryEndpoint()); }); } @Test static class AzureResourceManagerExt { static AzureResourceManager getAzureResourceManager() { return mock(AzureResourceManager.class); } } }
class AzureResourceManagerAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureResourceManagerAutoConfiguration.class)); @Test void testAzureResourceManagerDisabled() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=false") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithoutTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=true") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.profile.tenant-id=test-tenant") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void testWithoutAzureResourceManagerClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceManager.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testWithoutAzureResourceMetadataClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceMetadata.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testAzureProfileWithAzureDefault() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, TestAzureResourceManager::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE.getActiveDirectoryEndpoint()); }); } @Test }
You mean the `tenant-id` and `subscription-id`? it's required for AzureResourceManagerAutoConfiguration, https://github.com/Azure/azure-sdk-for-java/blob/15dda6cdc3219e9128a4d5207cb66d891fd1baf8/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/resourcemanager/AzureResourceManagerAutoConfiguration.java#L25
void testAzureProfileWithAzureChina() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, AzureResourceManagerExt::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id", "spring.cloud.azure.profile.cloud=AZURE_CHINA" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE_CHINA.getActiveDirectoryEndpoint()); }); }
Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(),
void testAzureProfileWithAzureChina() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, TestAzureResourceManager::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id", "spring.cloud.azure.profile.cloud=AZURE_CHINA" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE_CHINA.getActiveDirectoryEndpoint()); }); }
class AzureResourceManagerAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureResourceManagerAutoConfiguration.class)); @Test void testAzureResourceManagerDisabled() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=false") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithoutTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=true") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.profile.tenant-id=test-tenant") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void testWithoutAzureResourceManagerClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceManager.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testWithoutAzureResourceMetadataClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceMetadata.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testAzureProfileWithAzureDefault() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, AzureResourceManagerExt::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE.getActiveDirectoryEndpoint()); }); } @Test static class AzureResourceManagerExt { static AzureResourceManager getAzureResourceManager() { return mock(AzureResourceManager.class); } } }
class AzureResourceManagerAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureResourceManagerAutoConfiguration.class)); @Test void testAzureResourceManagerDisabled() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=false") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithoutTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.resourcemanager.enabled=true") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void configureWithTenantId() { this.contextRunner .withPropertyValues("spring.cloud.azure.profile.tenant-id=test-tenant") .run(context -> { assertThat(context).doesNotHaveBean(AzureResourceManager.class); assertThat(context).doesNotHaveBean(AzureProfile.class); }); } @Test void testWithoutAzureResourceManagerClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceManager.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testWithoutAzureResourceMetadataClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(AzureResourceMetadata.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureProfile.class)); } @Test void testAzureProfileWithAzureDefault() { this.contextRunner .withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class) .withBean(AzureResourceManager.class, TestAzureResourceManager::getAzureResourceManager) .withPropertyValues( "spring.cloud.azure.profile.tenant-id=test-tenant-id", "spring.cloud.azure.profile.subscription-id=test-subscription-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureProfile.class); AzureProfile azureProfile = context.getBean(AzureProfile.class); Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(), AZURE.getActiveDirectoryEndpoint()); }); } @Test }
Should we encode the valueStr to ensure we have a valid json? If `valueStr` contains a `"` it will result in an invalid json.
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\"") .append(key) .append("\"") .append(":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { return formatter.append(value); } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } return formatter.append("\"") .append(valueStr) .append("\""); }
.append(valueStr)
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(key, formatter); formatter.append("\":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); return formatter; } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(valueStr, formatter); return formatter.append("\""); }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes {"key":"value"} json string to provided StringBuilder. */ }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. */ }
great catch! I went to the rabbit hole there and had to change things a bit (e.g. we have to format message first before we escape it (because if formatting anchor `{}`)
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\"") .append(key) .append("\"") .append(":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { return formatter.append(value); } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } return formatter.append("\"") .append(valueStr) .append("\""); }
.append(valueStr)
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(key, formatter); formatter.append("\":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); return formatter; } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(valueStr, formatter); return formatter.append("\""); }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes {"key":"value"} json string to provided StringBuilder. */ }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. */ }
Will this result in `long`, `bool` types formatted as string? `"key": "false"` instead of `"key": false`
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(key, formatter); formatter.append("\":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); return formatter; } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(valueStr, formatter); return formatter.append("\""); }
JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter);
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(key, formatter); formatter.append("\":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); return formatter; } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(valueStr, formatter); return formatter.append("\""); }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes {"key":"value"} json string to provided StringBuilder. */ }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. */ }
nope, I have a test for it as well
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(key, formatter); formatter.append("\":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); return formatter; } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(valueStr, formatter); return formatter.append("\""); }
JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter);
public StringBuilder writeKeyAndValue(StringBuilder formatter) { formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(key, formatter); formatter.append("\":"); String valueStr = null; if (value != null) { if (!(value instanceof String)) { JSON_STRING_ENCODER.quoteAsString(value.toString(), formatter); return formatter; } valueStr = (String) value; } else if (valueSupplier != null) { valueStr = valueSupplier.get(); } if (valueStr == null) { return formatter.append("null"); } formatter.append("\""); JSON_STRING_ENCODER.quoteAsString(valueStr, formatter); return formatter.append("\""); }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes {"key":"value"} json string to provided StringBuilder. */ }
class ContextKeyValuePair { private final String key; private final Object value; private final Supplier<String> valueSupplier; ContextKeyValuePair(String key, Object value) { this.key = key; this.value = value; this.valueSupplier = null; } ContextKeyValuePair(String key, Supplier<String> valueSupplier) { this.key = key; this.value = null; this.valueSupplier = valueSupplier; } /** * Writes "key":"value" json string to provided StringBuilder. */ }
I thought we were going to add standalone samples to showcase this? If we add it here, I think there could be confusion for our data gathering purposes about whether the customer was simply looking at a sample about how to analyze layout vs looking for how to use the spans to find related elements.
public static void main(final String[] args) throws IOException { DocumentAnalysisClient client = new DocumentAnalysisClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File selectionMarkDocument = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" + "sample-forms/forms/selectionMarkForm.pdf"); byte[] fileContent = Files.readAllBytes(selectionMarkDocument.toPath()); InputStream fileStream = new ByteArrayInputStream(fileContent); SyncPoller<DocumentOperationResult, AnalyzeResult> analyzeLayoutResultPoller = client.beginAnalyzeDocument("prebuilt-layout", fileStream, selectionMarkDocument.length()); AnalyzeResult analyzeLayoutResult = analyzeLayoutResultPoller.getFinalResult(); analyzeLayoutResult.getPages().forEach(documentPage -> { System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n", documentPage.getWidth(), documentPage.getHeight(), documentPage.getUnit()); documentPage.getLines().forEach(documentLine -> { System.out.printf("Line '%s' is within a bounding box %s.%n", documentLine.getContent(), documentLine.getBoundingBox().toString()); List<DocumentWord> containedWords = getWordsInALine(documentLine, documentPage.getWords()); System.out.printf("Total number of words in the line: %d.%n", containedWords.size()); System.out.printf("Words contained in the line are: %s.%n", containedWords.stream().map(DocumentWord::getContent).collect(Collectors.toList())); }); documentPage.getWords().forEach(documentWord -> System.out.printf("Word '%s' has a confidence score of %.2f.%n", documentWord.getContent(), documentWord.getConfidence())); documentPage.getSelectionMarks().forEach(documentSelectionMark -> System.out.printf("Selection mark is '%s' and is within a bounding box %s with confidence %.2f.%n", documentSelectionMark.getState().toString(), documentSelectionMark.getBoundingBox().toString(), documentSelectionMark.getConfidence())); }); List<DocumentTable> tables = analyzeLayoutResult.getTables(); for (int i = 0; i < tables.size(); i++) { DocumentTable documentTable = tables.get(i); System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(), documentTable.getColumnCount()); documentTable.getCells().forEach(documentTableCell -> { System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(), documentTableCell.getRowIndex(), documentTableCell.getColumnIndex()); }); System.out.println(); } analyzeLayoutResult.getStyles().forEach(documentStyle -> System.out.printf("Document is handwritten %s.%n", documentStyle.isHandwritten())); }
List<DocumentWord> containedWords = getWordsInALine(documentLine, documentPage.getWords());
public static void main(final String[] args) throws IOException { DocumentAnalysisClient client = new DocumentAnalysisClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File selectionMarkDocument = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" + "sample-forms/forms/selectionMarkForm.pdf"); byte[] fileContent = Files.readAllBytes(selectionMarkDocument.toPath()); InputStream fileStream = new ByteArrayInputStream(fileContent); SyncPoller<DocumentOperationResult, AnalyzeResult> analyzeLayoutResultPoller = client.beginAnalyzeDocument("prebuilt-layout", fileStream, selectionMarkDocument.length()); AnalyzeResult analyzeLayoutResult = analyzeLayoutResultPoller.getFinalResult(); analyzeLayoutResult.getPages().forEach(documentPage -> { System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n", documentPage.getWidth(), documentPage.getHeight(), documentPage.getUnit()); documentPage.getLines().forEach(documentLine -> System.out.printf("Line '%s; is within a bounding box %s.%n", documentLine.getContent(), documentLine.getBoundingBox().toString())); documentPage.getWords().forEach(documentWord -> System.out.printf("Word '%s' has a confidence score of %.2f%n.", documentWord.getContent(), documentWord.getConfidence())); documentPage.getSelectionMarks().forEach(documentSelectionMark -> System.out.printf("Selection mark is '%s' and is within a bounding box %s with confidence %.2f.%n", documentSelectionMark.getState().toString(), documentSelectionMark.getBoundingBox().toString(), documentSelectionMark.getConfidence())); }); List<DocumentTable> tables = analyzeLayoutResult.getTables(); for (int i = 0; i < tables.size(); i++) { DocumentTable documentTable = tables.get(i); System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(), documentTable.getColumnCount()); documentTable.getCells().forEach(documentTableCell -> { System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(), documentTableCell.getRowIndex(), documentTableCell.getColumnIndex()); }); System.out.println(); } analyzeLayoutResult.getStyles().forEach(documentStyle -> System.out.printf("Document is handwritten %s%n.", documentStyle.isHandwritten())); }
class AnalyzeLayout { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ private static List<DocumentWord> getWordsInALine(DocumentLine documentLine, List<DocumentWord> pageWords) { List<DocumentWord> containedWords = new ArrayList<>(); pageWords.forEach(documentWord -> { documentLine.getSpans().forEach(documentSpan -> { if ((documentWord.getSpan().getOffset() >= documentSpan.getOffset()) && ((documentWord.getSpan().getOffset() + documentWord.getSpan().getLength()) <= (documentSpan.getOffset() + documentSpan.getLength()))) { containedWords.add(documentWord); } }); }); return containedWords; } }
class AnalyzeLayout { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
yeah, I was a bit confused. But yes, for telemetry reasons I think it will make sense to have this as a standalone sample.
public static void main(final String[] args) throws IOException { DocumentAnalysisClient client = new DocumentAnalysisClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File selectionMarkDocument = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" + "sample-forms/forms/selectionMarkForm.pdf"); byte[] fileContent = Files.readAllBytes(selectionMarkDocument.toPath()); InputStream fileStream = new ByteArrayInputStream(fileContent); SyncPoller<DocumentOperationResult, AnalyzeResult> analyzeLayoutResultPoller = client.beginAnalyzeDocument("prebuilt-layout", fileStream, selectionMarkDocument.length()); AnalyzeResult analyzeLayoutResult = analyzeLayoutResultPoller.getFinalResult(); analyzeLayoutResult.getPages().forEach(documentPage -> { System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n", documentPage.getWidth(), documentPage.getHeight(), documentPage.getUnit()); documentPage.getLines().forEach(documentLine -> { System.out.printf("Line '%s' is within a bounding box %s.%n", documentLine.getContent(), documentLine.getBoundingBox().toString()); List<DocumentWord> containedWords = getWordsInALine(documentLine, documentPage.getWords()); System.out.printf("Total number of words in the line: %d.%n", containedWords.size()); System.out.printf("Words contained in the line are: %s.%n", containedWords.stream().map(DocumentWord::getContent).collect(Collectors.toList())); }); documentPage.getWords().forEach(documentWord -> System.out.printf("Word '%s' has a confidence score of %.2f.%n", documentWord.getContent(), documentWord.getConfidence())); documentPage.getSelectionMarks().forEach(documentSelectionMark -> System.out.printf("Selection mark is '%s' and is within a bounding box %s with confidence %.2f.%n", documentSelectionMark.getState().toString(), documentSelectionMark.getBoundingBox().toString(), documentSelectionMark.getConfidence())); }); List<DocumentTable> tables = analyzeLayoutResult.getTables(); for (int i = 0; i < tables.size(); i++) { DocumentTable documentTable = tables.get(i); System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(), documentTable.getColumnCount()); documentTable.getCells().forEach(documentTableCell -> { System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(), documentTableCell.getRowIndex(), documentTableCell.getColumnIndex()); }); System.out.println(); } analyzeLayoutResult.getStyles().forEach(documentStyle -> System.out.printf("Document is handwritten %s.%n", documentStyle.isHandwritten())); }
List<DocumentWord> containedWords = getWordsInALine(documentLine, documentPage.getWords());
public static void main(final String[] args) throws IOException { DocumentAnalysisClient client = new DocumentAnalysisClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File selectionMarkDocument = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" + "sample-forms/forms/selectionMarkForm.pdf"); byte[] fileContent = Files.readAllBytes(selectionMarkDocument.toPath()); InputStream fileStream = new ByteArrayInputStream(fileContent); SyncPoller<DocumentOperationResult, AnalyzeResult> analyzeLayoutResultPoller = client.beginAnalyzeDocument("prebuilt-layout", fileStream, selectionMarkDocument.length()); AnalyzeResult analyzeLayoutResult = analyzeLayoutResultPoller.getFinalResult(); analyzeLayoutResult.getPages().forEach(documentPage -> { System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n", documentPage.getWidth(), documentPage.getHeight(), documentPage.getUnit()); documentPage.getLines().forEach(documentLine -> System.out.printf("Line '%s; is within a bounding box %s.%n", documentLine.getContent(), documentLine.getBoundingBox().toString())); documentPage.getWords().forEach(documentWord -> System.out.printf("Word '%s' has a confidence score of %.2f%n.", documentWord.getContent(), documentWord.getConfidence())); documentPage.getSelectionMarks().forEach(documentSelectionMark -> System.out.printf("Selection mark is '%s' and is within a bounding box %s with confidence %.2f.%n", documentSelectionMark.getState().toString(), documentSelectionMark.getBoundingBox().toString(), documentSelectionMark.getConfidence())); }); List<DocumentTable> tables = analyzeLayoutResult.getTables(); for (int i = 0; i < tables.size(); i++) { DocumentTable documentTable = tables.get(i); System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(), documentTable.getColumnCount()); documentTable.getCells().forEach(documentTableCell -> { System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(), documentTableCell.getRowIndex(), documentTableCell.getColumnIndex()); }); System.out.println(); } analyzeLayoutResult.getStyles().forEach(documentStyle -> System.out.printf("Document is handwritten %s%n.", documentStyle.isHandwritten())); }
class AnalyzeLayout { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ private static List<DocumentWord> getWordsInALine(DocumentLine documentLine, List<DocumentWord> pageWords) { List<DocumentWord> containedWords = new ArrayList<>(); pageWords.forEach(documentWord -> { documentLine.getSpans().forEach(documentSpan -> { if ((documentWord.getSpan().getOffset() >= documentSpan.getOffset()) && ((documentWord.getSpan().getOffset() + documentWord.getSpan().getLength()) <= (documentSpan.getOffset() + documentSpan.getLength()))) { containedWords.add(documentWord); } }); }); return containedWords; } }
class AnalyzeLayout { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
format
public void canRedisVersionUpdate(){ RedisCache.MajorVersion redisVersion = RedisCache.MajorVersion.V4; RedisCache redisCache = redisManager .redisCaches() .define(rrName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withBasicSku() .withRedisVersion(redisVersion) .create() ; Assertions.assertTrue(redisCache.redisVersion().startsWith(redisVersion.getValue())); redisVersion = RedisCache.MajorVersion.V6; redisCache = redisCache.update() .withRedisVersion(redisVersion) .apply(); ResourceManagerUtils.sleep(Duration.ofSeconds(300)); redisCache = redisCache.refresh(); Assertions.assertTrue(redisCache.redisVersion().startsWith(redisVersion.getValue())); }
;
public void canRedisVersionUpdate() { RedisCache.RedisVersion redisVersion = RedisCache.RedisVersion.V4; RedisCache redisCache = redisManager .redisCaches() .define(rrName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withBasicSku() .withRedisVersion(redisVersion) .create(); Assertions.assertTrue(redisCache.redisVersion().startsWith(redisVersion.getValue())); redisVersion = RedisCache.RedisVersion.V6; redisCache = redisCache.update() .withRedisVersion(redisVersion) .apply(); ResourceManagerUtils.sleep(Duration.ofSeconds(300)); redisCache = redisCache.refresh(); Assertions.assertTrue(redisCache.redisVersion().startsWith(redisVersion.getValue())); }
class RedisCacheOperationsTests extends RedisManagementTest { @Test @SuppressWarnings("unchecked") public void canCRUDRedisCache() throws Exception { Creatable<ResourceGroup> resourceGroups = resourceManager.resourceGroups().define(rgNameSecond).withRegion(Region.US_CENTRAL); Creatable<RedisCache> redisCacheDefinition1 = redisManager .redisCaches() .define(rrName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withBasicSku(); Creatable<RedisCache> redisCacheDefinition2 = redisManager .redisCaches() .define(rrNameSecond) .withRegion(Region.US_CENTRAL) .withNewResourceGroup(resourceGroups) .withPremiumSku() .withShardCount(2) .withPatchSchedule(DayOfWeek.SUNDAY, 10, Duration.ofMinutes(302)); Creatable<RedisCache> redisCacheDefinition3 = redisManager .redisCaches() .define(rrNameThird) .withRegion(Region.US_CENTRAL) .withNewResourceGroup(resourceGroups) .withPremiumSku(2) .withRedisConfiguration("maxclients", "2") .withNonSslPort() .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40"); CreatedResources<RedisCache> batchRedisCaches = redisManager.redisCaches().create(redisCacheDefinition1, redisCacheDefinition2, redisCacheDefinition3); RedisCache redisCache = batchRedisCaches.get(redisCacheDefinition1.key()); RedisCache redisCachePremium = batchRedisCaches.get(redisCacheDefinition3.key()); Assertions.assertEquals(rgName, redisCache.resourceGroupName()); Assertions.assertEquals(SkuName.BASIC, redisCache.sku().name()); RedisCachePremium premiumCache = redisCachePremium.asPremium(); Assertions.assertEquals(SkuFamily.P, premiumCache.sku().family()); Assertions.assertEquals(2, premiumCache.firewallRules().size()); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule1")); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule2")); premiumCache .update() .withRedisConfiguration("maxclients", "3") .withoutFirewallRule("rule1") .withFirewallRule("rule3", "192.168.0.10", "192.168.0.104") .withoutMinimumTlsVersion() .apply(); Thread.sleep(10000); premiumCache.refresh(); Assertions.assertEquals(2, premiumCache.firewallRules().size()); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule2")); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule3")); Assertions.assertFalse(premiumCache.firewallRules().containsKey("rule1")); premiumCache.update().withoutRedisConfiguration("maxclients").apply(); premiumCache.update().withoutRedisConfiguration().apply(); Assertions.assertEquals(0, premiumCache.patchSchedules().size()); premiumCache.update().withPatchSchedule(DayOfWeek.MONDAY, 1).withPatchSchedule(DayOfWeek.TUESDAY, 5).apply(); Assertions.assertEquals(2, premiumCache.patchSchedules().size()); premiumCache.forceReboot(RebootType.ALL_NODES); List<ScheduleEntry> patchSchedule = premiumCache.listPatchSchedules(); Assertions.assertEquals(2, patchSchedule.size()); premiumCache.deletePatchSchedule(); patchSchedule = redisManager.redisCaches().getById(premiumCache.id()).asPremium().listPatchSchedules(); Assertions.assertNull(patchSchedule); List<RedisCache> redisCaches = redisManager.redisCaches().listByResourceGroup(rgName).stream().collect(Collectors.toList()); boolean found = false; for (RedisCache existingRedisCache : redisCaches) { if (existingRedisCache.name().equals(rrName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, redisCaches.size()); redisCaches = redisManager.redisCaches().list().stream().collect(Collectors.toList()); found = false; for (RedisCache existingRedisCache : redisCaches) { if (existingRedisCache.name().equals(rrName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertTrue(redisCaches.size() >= 3); RedisCache redisCacheGet = redisManager.redisCaches().getByResourceGroup(rgName, rrName); Assertions.assertNotNull(redisCacheGet); Assertions.assertEquals(redisCache.id(), redisCacheGet.id()); Assertions.assertEquals(redisCache.provisioningState(), redisCacheGet.provisioningState()); RedisAccessKeys redisKeys = redisCache.keys(); Assertions.assertNotNull(redisKeys); Assertions.assertNotNull(redisKeys.primaryKey()); Assertions.assertNotNull(redisKeys.secondaryKey()); RedisAccessKeys oldKeys = redisCache.refreshKeys(); RedisAccessKeys updatedPrimaryKey = redisCache.regenerateKey(RedisKeyType.PRIMARY); RedisAccessKeys updatedSecondaryKey = redisCache.regenerateKey(RedisKeyType.SECONDARY); Assertions.assertNotNull(oldKeys); Assertions.assertNotNull(updatedPrimaryKey); Assertions.assertNotNull(updatedSecondaryKey); if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKeys.primaryKey(), updatedPrimaryKey.primaryKey()); Assertions.assertEquals(oldKeys.secondaryKey(), updatedPrimaryKey.secondaryKey()); Assertions.assertNotEquals(oldKeys.secondaryKey(), updatedSecondaryKey.secondaryKey()); Assertions.assertNotEquals(updatedPrimaryKey.secondaryKey(), updatedSecondaryKey.secondaryKey()); Assertions.assertEquals(updatedPrimaryKey.primaryKey(), updatedSecondaryKey.primaryKey()); } redisCache = redisCache.update().withStandardSku().apply(); Assertions.assertEquals(SkuName.STANDARD, redisCache.sku().name()); Assertions.assertEquals(SkuFamily.C, redisCache.sku().family()); try { redisCache.update().withBasicSku(1).apply(); Assertions.fail(); } catch (ManagementException e) { } redisCache.refresh(); redisManager.redisCaches().deleteById(redisCache.id()); /*premiumCache.exportData(storageAccount.name(),"snapshot1"); premiumCache.importData(Arrays.asList("snapshot1"));*/ } @Test @Test public void canCRUDLinkedServers() throws Exception { RedisCache rgg = redisManager .redisCaches() .define(rrNameThird) .withRegion(Region.US_CENTRAL) .withNewResourceGroup(rgNameSecond) .withPremiumSku(2) .withPatchSchedule(DayOfWeek.SATURDAY, 5, Duration.ofHours(5)) .withRedisConfiguration("maxclients", "2") .withNonSslPort() .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40") .create(); RedisCache rggLinked = redisManager .redisCaches() .define(rrNameSecond) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgNameSecond) .withPremiumSku(2) .create(); Assertions.assertNotNull(rgg); Assertions.assertNotNull(rggLinked); RedisCachePremium premiumRgg = rgg.asPremium(); String llName = premiumRgg.addLinkedServer(rggLinked.id(), rggLinked.regionName(), ReplicationRole.PRIMARY); Assertions.assertEquals(ResourceUtils.nameFromResourceId(rggLinked.id()), llName); Map<String, ReplicationRole> linkedServers = premiumRgg.listLinkedServers(); Assertions.assertEquals(1, linkedServers.size()); Assertions.assertTrue(linkedServers.keySet().contains(llName)); Assertions.assertEquals(ReplicationRole.PRIMARY, linkedServers.get(llName)); ReplicationRole repRole = premiumRgg.getLinkedServerRole(llName); Assertions.assertEquals(ReplicationRole.PRIMARY, repRole); premiumRgg.removeLinkedServer(llName); rgg.update().withoutPatchSchedule().apply(); rggLinked.update().withFirewallRule("rulesmhule", "192.168.1.10", "192.168.1.20").apply(); linkedServers = premiumRgg.listLinkedServers(); Assertions.assertEquals(0, linkedServers.size()); } }
class RedisCacheOperationsTests extends RedisManagementTest { @Test @SuppressWarnings("unchecked") public void canCRUDRedisCache() throws Exception { Creatable<ResourceGroup> resourceGroups = resourceManager.resourceGroups().define(rgNameSecond).withRegion(Region.US_CENTRAL); Creatable<RedisCache> redisCacheDefinition1 = redisManager .redisCaches() .define(rrName) .withRegion(Region.ASIA_EAST) .withNewResourceGroup(rgName) .withBasicSku(); Creatable<RedisCache> redisCacheDefinition2 = redisManager .redisCaches() .define(rrNameSecond) .withRegion(Region.US_CENTRAL) .withNewResourceGroup(resourceGroups) .withPremiumSku() .withShardCount(2) .withPatchSchedule(DayOfWeek.SUNDAY, 10, Duration.ofMinutes(302)); Creatable<RedisCache> redisCacheDefinition3 = redisManager .redisCaches() .define(rrNameThird) .withRegion(Region.US_CENTRAL) .withNewResourceGroup(resourceGroups) .withPremiumSku(2) .withRedisConfiguration("maxclients", "2") .withNonSslPort() .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40"); CreatedResources<RedisCache> batchRedisCaches = redisManager.redisCaches().create(redisCacheDefinition1, redisCacheDefinition2, redisCacheDefinition3); RedisCache redisCache = batchRedisCaches.get(redisCacheDefinition1.key()); RedisCache redisCachePremium = batchRedisCaches.get(redisCacheDefinition3.key()); Assertions.assertEquals(rgName, redisCache.resourceGroupName()); Assertions.assertEquals(SkuName.BASIC, redisCache.sku().name()); RedisCachePremium premiumCache = redisCachePremium.asPremium(); Assertions.assertEquals(SkuFamily.P, premiumCache.sku().family()); Assertions.assertEquals(2, premiumCache.firewallRules().size()); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule1")); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule2")); premiumCache .update() .withRedisConfiguration("maxclients", "3") .withoutFirewallRule("rule1") .withFirewallRule("rule3", "192.168.0.10", "192.168.0.104") .withoutMinimumTlsVersion() .apply(); ResourceManagerUtils.sleep(Duration.ofSeconds(10)); premiumCache.refresh(); Assertions.assertEquals(2, premiumCache.firewallRules().size()); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule2")); Assertions.assertTrue(premiumCache.firewallRules().containsKey("rule3")); Assertions.assertFalse(premiumCache.firewallRules().containsKey("rule1")); premiumCache.update().withoutRedisConfiguration("maxclients").apply(); premiumCache.update().withoutRedisConfiguration().apply(); Assertions.assertEquals(0, premiumCache.patchSchedules().size()); premiumCache.update().withPatchSchedule(DayOfWeek.MONDAY, 1).withPatchSchedule(DayOfWeek.TUESDAY, 5).apply(); Assertions.assertEquals(2, premiumCache.patchSchedules().size()); premiumCache.forceReboot(RebootType.ALL_NODES); List<ScheduleEntry> patchSchedule = premiumCache.listPatchSchedules(); Assertions.assertEquals(2, patchSchedule.size()); premiumCache.deletePatchSchedule(); patchSchedule = redisManager.redisCaches().getById(premiumCache.id()).asPremium().listPatchSchedules(); Assertions.assertNull(patchSchedule); List<RedisCache> redisCaches = redisManager.redisCaches().listByResourceGroup(rgName).stream().collect(Collectors.toList()); boolean found = false; for (RedisCache existingRedisCache : redisCaches) { if (existingRedisCache.name().equals(rrName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertEquals(1, redisCaches.size()); redisCaches = redisManager.redisCaches().list().stream().collect(Collectors.toList()); found = false; for (RedisCache existingRedisCache : redisCaches) { if (existingRedisCache.name().equals(rrName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertTrue(redisCaches.size() >= 3); RedisCache redisCacheGet = redisManager.redisCaches().getByResourceGroup(rgName, rrName); Assertions.assertNotNull(redisCacheGet); Assertions.assertEquals(redisCache.id(), redisCacheGet.id()); Assertions.assertEquals(redisCache.provisioningState(), redisCacheGet.provisioningState()); RedisAccessKeys redisKeys = redisCache.keys(); Assertions.assertNotNull(redisKeys); Assertions.assertNotNull(redisKeys.primaryKey()); Assertions.assertNotNull(redisKeys.secondaryKey()); RedisAccessKeys oldKeys = redisCache.refreshKeys(); RedisAccessKeys updatedPrimaryKey = redisCache.regenerateKey(RedisKeyType.PRIMARY); RedisAccessKeys updatedSecondaryKey = redisCache.regenerateKey(RedisKeyType.SECONDARY); Assertions.assertNotNull(oldKeys); Assertions.assertNotNull(updatedPrimaryKey); Assertions.assertNotNull(updatedSecondaryKey); if (!isPlaybackMode()) { Assertions.assertNotEquals(oldKeys.primaryKey(), updatedPrimaryKey.primaryKey()); Assertions.assertEquals(oldKeys.secondaryKey(), updatedPrimaryKey.secondaryKey()); Assertions.assertNotEquals(oldKeys.secondaryKey(), updatedSecondaryKey.secondaryKey()); Assertions.assertNotEquals(updatedPrimaryKey.secondaryKey(), updatedSecondaryKey.secondaryKey()); Assertions.assertEquals(updatedPrimaryKey.primaryKey(), updatedSecondaryKey.primaryKey()); } redisCache = redisCache.update().withStandardSku().apply(); Assertions.assertEquals(SkuName.STANDARD, redisCache.sku().name()); Assertions.assertEquals(SkuFamily.C, redisCache.sku().family()); try { redisCache.update().withBasicSku(1).apply(); Assertions.fail(); } catch (ManagementException e) { } redisCache.refresh(); redisManager.redisCaches().deleteById(redisCache.id()); /*premiumCache.exportData(storageAccount.name(),"snapshot1"); premiumCache.importData(Arrays.asList("snapshot1"));*/ } @Test @Test public void canCRUDLinkedServers() throws Exception { RedisCache rgg = redisManager .redisCaches() .define(rrNameThird) .withRegion(Region.US_CENTRAL) .withNewResourceGroup(rgNameSecond) .withPremiumSku(2) .withPatchSchedule(DayOfWeek.SATURDAY, 5, Duration.ofHours(5)) .withRedisConfiguration("maxclients", "2") .withNonSslPort() .withFirewallRule("rule1", "192.168.0.1", "192.168.0.4") .withFirewallRule("rule2", "192.168.0.10", "192.168.0.40") .create(); RedisCache rggLinked = redisManager .redisCaches() .define(rrNameSecond) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgNameSecond) .withPremiumSku(2) .create(); Assertions.assertNotNull(rgg); Assertions.assertNotNull(rggLinked); RedisCachePremium premiumRgg = rgg.asPremium(); String llName = premiumRgg.addLinkedServer(rggLinked.id(), rggLinked.regionName(), ReplicationRole.PRIMARY); Assertions.assertEquals(ResourceUtils.nameFromResourceId(rggLinked.id()), llName); Map<String, ReplicationRole> linkedServers = premiumRgg.listLinkedServers(); Assertions.assertEquals(1, linkedServers.size()); Assertions.assertTrue(linkedServers.keySet().contains(llName)); Assertions.assertEquals(ReplicationRole.PRIMARY, linkedServers.get(llName)); ReplicationRole repRole = premiumRgg.getLinkedServerRole(llName); Assertions.assertEquals(ReplicationRole.PRIMARY, repRole); premiumRgg.removeLinkedServer(llName); rgg.update().withoutPatchSchedule().apply(); rggLinked.update().withFirewallRule("rulesmhule", "192.168.1.10", "192.168.1.20").apply(); linkedServers = premiumRgg.listLinkedServers(); Assertions.assertEquals(0, linkedServers.size()); } }