comment stringlengths 1 45k | method_body stringlengths 23 281k | target_code stringlengths 0 5.16k | method_body_after stringlengths 12 281k | context_before stringlengths 8 543k | context_after stringlengths 8 543k |
|---|---|---|---|---|---|
this changes is for not to cause NPE in Arrays.asList(notNull). The default value for `this.recognizeEntitiesOptions` is null. We don't want to sent an empty list to service. which means different than sent the null. ``` @SafeVarargs public static <T> List<T> asList(T... a) { return new Arrays.ArrayList(a); } ``` | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} |
Awesome! | private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
return new JobManifestTasks()
.setEntityRecognitionTasks(actions.getRecognizeEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntitiesTask entitiesTask = new EntitiesTask();
entitiesTask.setParameters(
new EntitiesTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType())));
return entitiesTask;
}).collect(Collectors.toList()))
.setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizePiiEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final PiiTask piiTask = new PiiTask();
piiTask.setParameters(
new PiiTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType()))
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))
);
return piiTask;
}).collect(Collectors.toList()))
.setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesOptions() == null ? null
: StreamSupport.stream(actions.getExtractKeyPhrasesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask();
keyPhrasesTask.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return keyPhrasesTask;
}).collect(Collectors.toList()))
.setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeLinkedEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntityLinkingTask entityLinkingTask = new EntityLinkingTask();
entityLinkingTask.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return entityLinkingTask;
}).collect(Collectors.toList()))
.setSentimentAnalysisTasks(actions.getAnalyzeSentimentOptions() == null ? null
: StreamSupport.stream(actions.getAnalyzeSentimentOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask();
sentimentAnalysisTask.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(getNotNullModelVersion(action.getModelVersion()))
);
return sentimentAnalysisTask;
}).collect(Collectors.toList()));
} | new SentimentAnalysisTaskParameters() | private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
return new JobManifestTasks()
.setEntityRecognitionTasks(actions.getRecognizeEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntitiesTask entitiesTask = new EntitiesTask();
entitiesTask.setParameters(
new EntitiesTaskParameters()
.setModelVersion(action.getModelVersion())
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType())));
return entitiesTask;
}).collect(Collectors.toList()))
.setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizePiiEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final PiiTask piiTask = new PiiTask();
piiTask.setParameters(
new PiiTaskParameters()
.setModelVersion(action.getModelVersion())
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(getNonNullStringIndexType(action.getStringIndexType()))
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))
);
return piiTask;
}).collect(Collectors.toList()))
.setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesOptions() == null ? null
: StreamSupport.stream(actions.getExtractKeyPhrasesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask();
keyPhrasesTask.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(action.getModelVersion())
);
return keyPhrasesTask;
}).collect(Collectors.toList()))
.setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesOptions() == null ? null
: StreamSupport.stream(actions.getRecognizeLinkedEntitiesOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final EntityLinkingTask entityLinkingTask = new EntityLinkingTask();
entityLinkingTask.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(action.getModelVersion())
);
return entityLinkingTask;
}).collect(Collectors.toList()))
.setSentimentAnalysisTasks(actions.getAnalyzeSentimentOptions() == null ? null
: StreamSupport.stream(actions.getAnalyzeSentimentOptions().spliterator(), false).map(
action -> {
if (action == null) {
return null;
}
final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask();
sentimentAnalysisTask.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(action.getModelVersion())
);
return sentimentAnalysisTask;
}).collect(Collectors.toList()));
} | 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 REGEX_ACTION_ERROR_TARGET = "
+ "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)";
private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class);
private final TextAnalyticsClientImpl service;
AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
PollerFlux<AnalyzeActionsOperationDetail, PagedFlux<AnalyzeActionsResult>> 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, PagedIterable<AnalyzeActionsResult>> 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 PagedIterable<>(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
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<PagedFlux<AnalyzeActionsResult>>>
fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeActionsResult>>> 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<PagedIterable<AnalyzeActionsResult>>>
fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
PagedFlux<AnalyzeActionsResult> getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new PagedFlux<>(
() -> getPage(null, operationId, top, skip, showStats, context),
continuationToken -> getPage(continuationToken, operationId, top, skip, showStats, context));
}
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();
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<>();
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.setResult(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.setResult(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.setResult(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.setResult(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.setResult(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.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 {
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();
final RequestStatistics requestStatistics = analyzeJobState.getStatistics();
TextDocumentBatchStatistics batchStatistics = null;
if (requestStatistics != null) {
batchStatistics = new TextDocumentBatchStatistics(
requestStatistics.getDocumentsCount(), requestStatistics.getErroneousDocumentsCount(),
requestStatistics.getValidDocumentsCount(), requestStatistics.getTransactionsCount()
);
}
AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, batchStatistics);
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
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 getNotNullModelVersion(String modelVersion) {
return modelVersion == null ? "latest" : modelVersion;
}
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 Pattern pattern = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE);
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 REGEX_ACTION_ERROR_TARGET = "
+ "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)";
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, PagedFlux<AnalyzeActionsResult>> 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, PagedIterable<AnalyzeActionsResult>> 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 PagedIterable<>(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
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<PagedFlux<AnalyzeActionsResult>>>
fetchingOperation(Function<String, Mono<PagedFlux<AnalyzeActionsResult>>> 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<PagedIterable<AnalyzeActionsResult>>>
fetchingOperationIterable(Function<String, Mono<PagedIterable<AnalyzeActionsResult>>> fetchingFunction) {
return pollingContext -> {
try {
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
PagedFlux<AnalyzeActionsResult> getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new PagedFlux<>(
() -> getPage(null, operationId, top, skip, showStats, context),
continuationToken -> getPage(continuationToken, operationId, top, skip, showStats, context));
}
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();
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<>();
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.setResult(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.setResult(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.setResult(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.setResult(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.setResult(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.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 {
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();
final RequestStatistics requestStatistics = analyzeJobState.getStatistics();
TextDocumentBatchStatistics batchStatistics = null;
if (requestStatistics != null) {
batchStatistics = new TextDocumentBatchStatistics(
requestStatistics.getDocumentsCount(), requestStatistics.getErroneousDocumentsCount(),
requestStatistics.getValidDocumentsCount(), requestStatistics.getTransactionsCount()
);
}
AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, batchStatistics);
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
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;
}
} |
to make sure I understand.. was this a bug and now it is fixed? or this is a proactive change to avoid a possible bug in the future. If it is the first case, see if it is important enough to mention it in the changelog. | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} |
Yeah. It is a NPE bug. Will add it to CHANGELOG | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null | public TextAnalyticsActions setRecognizeEntitiesOptions(RecognizeEntitiesOptions... recognizeEntitiesOptions) {
this.recognizeEntitiesOptions = recognizeEntitiesOptions == null ? null
: Arrays.asList(recognizeEntitiesOptions);
return this;
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} | class TextAnalyticsActions {
private String displayName;
private Iterable<RecognizeEntitiesOptions> recognizeEntitiesOptions;
private Iterable<RecognizeLinkedEntitiesOptions> recognizeLinkedEntitiesOptions;
private Iterable<RecognizePiiEntitiesOptions> recognizePiiEntitiesOptions;
private Iterable<ExtractKeyPhrasesOptions> extractKeyPhrasesOptions;
private Iterable<AnalyzeSentimentOptions> analyzeSentimentOptions;
/**
* Get the custom name for the actions.
*
* @return the custom name for the actions.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the custom name for the actions.
*
* @param displayName the custom name for the actions.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizeEntitiesOptions} to be executed.
*/
public Iterable<RecognizeEntitiesOptions> getRecognizeEntitiesOptions() {
return this.recognizeEntitiesOptions;
}
/**
* Set the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @param recognizeEntitiesOptions the list of {@link RecognizeEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizeLinkedEntitiesOptions> getRecognizeLinkedEntitiesOptions() {
return this.recognizeLinkedEntitiesOptions;
}
/**
* Set the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @param recognizeLinkedEntitiesOptions the list of {@link RecognizeLinkedEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizeLinkedEntitiesOptions(
RecognizeLinkedEntitiesOptions... recognizeLinkedEntitiesOptions) {
this.recognizeLinkedEntitiesOptions = recognizeLinkedEntitiesOptions == null ? null
: Arrays.asList(recognizeLinkedEntitiesOptions);
return this;
}
/**
* Get the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the list of {@link RecognizePiiEntitiesOptions} to be executed.
*/
public Iterable<RecognizePiiEntitiesOptions> getRecognizePiiEntitiesOptions() {
return this.recognizePiiEntitiesOptions;
}
/**
* Set the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @param recognizePiiEntitiesOptions the list of {@link RecognizePiiEntitiesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setRecognizePiiEntitiesOptions(
RecognizePiiEntitiesOptions... recognizePiiEntitiesOptions) {
this.recognizePiiEntitiesOptions = recognizePiiEntitiesOptions == null ? null
: Arrays.asList(recognizePiiEntitiesOptions);
return this;
}
/**
* Get the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the list of {@link ExtractKeyPhrasesOptions} to be executed.
*/
public Iterable<ExtractKeyPhrasesOptions> getExtractKeyPhrasesOptions() {
return this.extractKeyPhrasesOptions;
}
/**
* Set the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @param extractKeyPhrasesOptions the list of {@link ExtractKeyPhrasesOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setExtractKeyPhrasesOptions(ExtractKeyPhrasesOptions... extractKeyPhrasesOptions) {
this.extractKeyPhrasesOptions = extractKeyPhrasesOptions == null ? null
: Arrays.asList(extractKeyPhrasesOptions);
return this;
}
/**
* Get the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the list of {@link AnalyzeSentimentOptions} to be executed.
*/
public Iterable<AnalyzeSentimentOptions> getAnalyzeSentimentOptions() {
return this.analyzeSentimentOptions;
}
/**
* Set the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @param analyzeSentimentOptions the list of {@link AnalyzeSentimentOptions} to be executed.
*
* @return the {@link TextAnalyticsActions} object itself.
*/
public TextAnalyticsActions setAnalyzeSentimentOptions(AnalyzeSentimentOptions... analyzeSentimentOptions) {
this.analyzeSentimentOptions = analyzeSentimentOptions == null ? null : Arrays.asList(analyzeSentimentOptions);
return this;
}
} |
Do we want `LiveOnly` to be `RECORD` || `LIVE`, or `!PLAYBACK`. As RECORD will also run against Azure Storage | public void visitFeatureAnnotation(LiveOnly annotation, FeatureInfo feature) {
TestMode testMode = TestEnvironment.getInstance().getTestMode();
if (testMode != TestMode.LIVE) {
feature.skip(String.format("Test ignored in %s mode", testMode));
}
} | if (testMode != TestMode.LIVE) { | public void visitFeatureAnnotation(LiveOnly annotation, FeatureInfo feature) {
TestMode testMode = TestEnvironment.getInstance().getTestMode();
if (testMode != TestMode.LIVE) {
feature.skip(String.format("Test ignored in %s mode", testMode));
}
} | class LiveOnlyExtension implements IAnnotationDrivenExtension<LiveOnly> {
@Override
} | class LiveOnlyExtension implements IAnnotationDrivenExtension<LiveOnly> {
@Override
@Override
public void visitSpecAnnotation(LiveOnly annotation, SpecInfo spec) {
TestMode testMode = TestEnvironment.getInstance().getTestMode();
if (testMode != TestMode.LIVE) {
spec.skip(String.format("Test ignored in %s mode", testMode));
}
}
} |
just copied the style fron phoneNumbers Async tests | public void checkForRepeatabilityOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "checkForRepeatabilityOptions");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE).flatMap(
requestResponse -> {
return requestResponse.getRequest().getBody().last();
}
))
.assertNext(bodyBuff -> {
String bodyRequest = new String(bodyBuff.array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
assertTrue(bodyRequest.contains("repeatabilityFirstSent"));
})
.verifyComplete();
} | } | public void checkForRepeatabilityOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "checkForRepeatabilityOptions");
StepVerifier.create(
asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE)
.flatMap(requestResponse -> {
return requestResponse.getRequest().getBody().last();
})
).assertNext(bodyBuff -> {
String bodyRequest = new String(bodyBuff.array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
assertTrue(bodyRequest.contains("repeatabilityFirstSent"));
})
.verifyComplete();
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} |
I'd rather not `|| RECROD`. There's no point of collecting that recording. I'd rather create separate annotation for that case if it's needed (i.e. `NoPlayback`). Also, let's be consistent with https://github.com/Azure/azure-sdk-for-net/blob/1782afc0c90cd305dc7c6f9da559d9283f7a3b65/sdk/core/Azure.Core.TestFramework/src/LiveOnlyAttribute.cs#L28 so if somebody switches between isn't suddenly taken by surprise. | public void visitFeatureAnnotation(LiveOnly annotation, FeatureInfo feature) {
TestMode testMode = TestEnvironment.getInstance().getTestMode();
if (testMode != TestMode.LIVE) {
feature.skip(String.format("Test ignored in %s mode", testMode));
}
} | if (testMode != TestMode.LIVE) { | public void visitFeatureAnnotation(LiveOnly annotation, FeatureInfo feature) {
TestMode testMode = TestEnvironment.getInstance().getTestMode();
if (testMode != TestMode.LIVE) {
feature.skip(String.format("Test ignored in %s mode", testMode));
}
} | class LiveOnlyExtension implements IAnnotationDrivenExtension<LiveOnly> {
@Override
} | class LiveOnlyExtension implements IAnnotationDrivenExtension<LiveOnly> {
@Override
@Override
public void visitSpecAnnotation(LiveOnly annotation, SpecInfo spec) {
TestMode testMode = TestEnvironment.getInstance().getTestMode();
if (testMode != TestMode.LIVE) {
spec.skip(String.format("Test ignored in %s mode", testMode));
}
}
} |
`wPindows`? | public EncryptedFlux(int testCase, AsyncKeyEncryptionKey key, APISpec spec) throws InvalidKeyException {
this.testCase = testCase;
this.plainText = spec.getRandomData(DOWNLOAD_SIZE - 2);
EncryptedBlob encryptedBlob = new EncryptedBlobAsyncClient(
null, "https:
.encryptBlob(Flux.just(this.plainText)).block();
this.cipherText = APISpec.collectBytesInBuffer(encryptedBlob.getCiphertextFlux()).block();
this.encryptionData = encryptedBlob.getEncryptionData();
} | null, "https: | public EncryptedFlux(int testCase, AsyncKeyEncryptionKey key, APISpec spec) throws InvalidKeyException {
this.testCase = testCase;
this.plainText = spec.getRandomData(DOWNLOAD_SIZE - 2);
EncryptedBlob encryptedBlob = new EncryptedBlobAsyncClient(
null, "https:
.encryptBlob(Flux.just(this.plainText)).block();
this.cipherText = APISpec.collectBytesInBuffer(encryptedBlob.getCiphertextFlux()).block();
this.encryptionData = encryptedBlob.getEncryptionData();
} | class EncryptedFlux extends Flux<ByteBuffer> {
private ByteBuffer plainText;
private ByteBuffer cipherText;
private int testCase;
private EncryptionData encryptionData;
public static final int DATA_OFFSET = 10;
public static final int DATA_COUNT = 40;
private static final int DOWNLOAD_SIZE = 64;
/*
These constants correspond to the positions above.
ByteBuffer limit() is exclusive, which is why we add one to a limit if that byte is supposed to be included, as in
the case of the last byte of the offsetAdjustment.
*/
private static final int POSITION_ONE = 0;
private static final int POSITION_TWO = DATA_OFFSET / 2;
private static final int POSITION_THREE_POSITION = DATA_OFFSET - 1;
private static final int POSITION_THREE_LIMIT = POSITION_THREE_POSITION + 1;
private static final int POSITION_FOUR_POSITION = DATA_OFFSET;
private static final int POSITION_FOUR_LIMIT = POSITION_FOUR_POSITION + 1;
private static final int POSITION_FIVE = DATA_OFFSET + (DATA_COUNT / 2);
private static final int POSITION_SIX_POSITION = DATA_OFFSET + DATA_COUNT - 1;
private static final int POSITION_SIX_LIMIT = POSITION_SIX_POSITION + 1;
private static final int POSITION_SEVEN_POSITION = DATA_OFFSET + DATA_COUNT;
private static final int POSITION_SEVEN_LIMIT = POSITION_SEVEN_POSITION + 1;
private static final int POSITION_EIGHT = DOWNLOAD_SIZE - 10;
private static final int POSITION_NINE_POSITION = DOWNLOAD_SIZE - 1;
private static final int POSITION_NINE_LIMIT = POSITION_NINE_POSITION + 1;
/*
Test cases. Unfortunately because each case covers multiple combinations, the name of each case cannot provide
much insight into to the pairs being tested, but each is commented with the pairs that it tests. There are a
couple redundancies that are necessary to complete sending the entire data when one combination excludes using other
new combinations.
*/
public static final int CASE_ZERO = 0;
public static final int CASE_ONE = 1;
public static final int CASE_TWO = 2;
public static final int CASE_THREE = 3;
public static final int CASE_FOUR = 4;
public static final int CASE_FIVE = 5;
public static final int CASE_SIX = 6;
public static final int CASE_SEVEN = 7;
public static final int CASE_EIGHT = 8;
public static final int CASE_NINE = 9;
public static final int CASE_TEN = 10;
public static final int CASE_ELEVEN = 11;
public static final int CASE_TWELVE = 12;
public static final int CASE_THIRTEEN = 13;
public static final int CASE_FOURTEEN = 14;
public static final int CASE_FIFTEEN = 15;
public static final int CASE_SIXTEEN = 16;
public static final int CASE_SEVENTEEN = 17;
public static final int CASE_EIGHTEEN = 18;
public static final int CASE_NINETEEN = 19;
public static final int CASE_TWENTY = 20;
public static final int CASE_TWENTY_ONE = 21;
public static final int CASE_TWENTY_TWO = 22;
private void sendBuffs(List<Integer> positionArr, List<Integer> limitArr, Subscriber<? super ByteBuffer> s) {
for (int i = 0; i < positionArr.size(); i++) {
ByteBuffer next = this.cipherText.duplicate();
next.position(positionArr.get(i)).limit(limitArr.get(i));
s.onNext(next);
}
}
@Override
public void subscribe(CoreSubscriber<? super ByteBuffer> s) {
List<Integer> positionArr;
List<Integer> limitArr;
switch (this.testCase) {
case CASE_ZERO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_FOUR_POSITION, POSITION_FIVE,
POSITION_SEVEN_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_THREE_LIMIT, POSITION_FIVE, POSITION_SIX_LIMIT,
POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWO:
/*
Note here and in some cases below, without loss of generality, we use FOUR_LIMIT instead of FIVE for the
range 5/7. This is because if we did strictly 1/4 and 5/7, we would skip the values between the
constants that are set as positions 4 and 5. Using FOUR_LIMIT is equivalent in effect to using FIVE as
POSITION_FIVE is representative of any byte within the range.
*/
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_THREE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FOUR:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SIX:
positionArr = Arrays.asList(POSITION_ONE, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_SEVEN:
positionArr = Collections.singletonList(POSITION_ONE);
limitArr = Collections.singletonList(POSITION_NINE_LIMIT);
break;
case CASE_EIGHT:
case CASE_THIRTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO);
limitArr = Arrays.asList(POSITION_TWO, POSITION_NINE_LIMIT);
break;
case CASE_NINE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_ELEVEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWELVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_FOURTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_FOUR_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_FOUR_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIFTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SIX_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_SIXTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SEVENTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_EIGHTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_NINETEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_TWO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_NINE_LIMIT);
break;
default:
throw new IllegalStateException("Unexpected case number");
}
sendBuffs(positionArr, limitArr, s);
s.onComplete();
}
public ByteBuffer getPlainText() {
return this.plainText;
}
public EncryptionData getEncryptionData() {
return this.encryptionData;
}
} | class EncryptedFlux extends Flux<ByteBuffer> {
private ByteBuffer plainText;
private ByteBuffer cipherText;
private int testCase;
private EncryptionData encryptionData;
public static final int DATA_OFFSET = 10;
public static final int DATA_COUNT = 40;
private static final int DOWNLOAD_SIZE = 64;
/*
These constants correspond to the positions above.
ByteBuffer limit() is exclusive, which is why we add one to a limit if that byte is supposed to be included, as in
the case of the last byte of the offsetAdjustment.
*/
private static final int POSITION_ONE = 0;
private static final int POSITION_TWO = DATA_OFFSET / 2;
private static final int POSITION_THREE_POSITION = DATA_OFFSET - 1;
private static final int POSITION_THREE_LIMIT = POSITION_THREE_POSITION + 1;
private static final int POSITION_FOUR_POSITION = DATA_OFFSET;
private static final int POSITION_FOUR_LIMIT = POSITION_FOUR_POSITION + 1;
private static final int POSITION_FIVE = DATA_OFFSET + (DATA_COUNT / 2);
private static final int POSITION_SIX_POSITION = DATA_OFFSET + DATA_COUNT - 1;
private static final int POSITION_SIX_LIMIT = POSITION_SIX_POSITION + 1;
private static final int POSITION_SEVEN_POSITION = DATA_OFFSET + DATA_COUNT;
private static final int POSITION_SEVEN_LIMIT = POSITION_SEVEN_POSITION + 1;
private static final int POSITION_EIGHT = DOWNLOAD_SIZE - 10;
private static final int POSITION_NINE_POSITION = DOWNLOAD_SIZE - 1;
private static final int POSITION_NINE_LIMIT = POSITION_NINE_POSITION + 1;
/*
Test cases. Unfortunately because each case covers multiple combinations, the name of each case cannot provide
much insight into to the pairs being tested, but each is commented with the pairs that it tests. There are a
couple redundancies that are necessary to complete sending the entire data when one combination excludes using other
new combinations.
*/
public static final int CASE_ZERO = 0;
public static final int CASE_ONE = 1;
public static final int CASE_TWO = 2;
public static final int CASE_THREE = 3;
public static final int CASE_FOUR = 4;
public static final int CASE_FIVE = 5;
public static final int CASE_SIX = 6;
public static final int CASE_SEVEN = 7;
public static final int CASE_EIGHT = 8;
public static final int CASE_NINE = 9;
public static final int CASE_TEN = 10;
public static final int CASE_ELEVEN = 11;
public static final int CASE_TWELVE = 12;
public static final int CASE_THIRTEEN = 13;
public static final int CASE_FOURTEEN = 14;
public static final int CASE_FIFTEEN = 15;
public static final int CASE_SIXTEEN = 16;
public static final int CASE_SEVENTEEN = 17;
public static final int CASE_EIGHTEEN = 18;
public static final int CASE_NINETEEN = 19;
public static final int CASE_TWENTY = 20;
public static final int CASE_TWENTY_ONE = 21;
public static final int CASE_TWENTY_TWO = 22;
private void sendBuffs(List<Integer> positionArr, List<Integer> limitArr, Subscriber<? super ByteBuffer> s) {
for (int i = 0; i < positionArr.size(); i++) {
ByteBuffer next = this.cipherText.duplicate();
next.position(positionArr.get(i)).limit(limitArr.get(i));
s.onNext(next);
}
}
@Override
public void subscribe(CoreSubscriber<? super ByteBuffer> s) {
List<Integer> positionArr;
List<Integer> limitArr;
switch (this.testCase) {
case CASE_ZERO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_FOUR_POSITION, POSITION_FIVE,
POSITION_SEVEN_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_THREE_LIMIT, POSITION_FIVE, POSITION_SIX_LIMIT,
POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWO:
/*
Note here and in some cases below, without loss of generality, we use FOUR_LIMIT instead of FIVE for the
range 5/7. This is because if we did strictly 1/4 and 5/7, we would skip the values between the
constants that are set as positions 4 and 5. Using FOUR_LIMIT is equivalent in effect to using FIVE as
POSITION_FIVE is representative of any byte within the range.
*/
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_THREE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FOUR:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SIX:
positionArr = Arrays.asList(POSITION_ONE, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_SEVEN:
positionArr = Collections.singletonList(POSITION_ONE);
limitArr = Collections.singletonList(POSITION_NINE_LIMIT);
break;
case CASE_EIGHT:
case CASE_THIRTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO);
limitArr = Arrays.asList(POSITION_TWO, POSITION_NINE_LIMIT);
break;
case CASE_NINE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_ELEVEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWELVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_FOURTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_FOUR_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_FOUR_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIFTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SIX_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_SIXTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SEVENTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_EIGHTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_NINETEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_TWO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_NINE_LIMIT);
break;
default:
throw new IllegalStateException("Unexpected case number");
}
sendBuffs(positionArr, limitArr, s);
s.onComplete();
}
public ByteBuffer getPlainText() {
return this.plainText;
}
public EncryptionData getEncryptionData() {
return this.encryptionData;
}
} |
whoops typo | public EncryptedFlux(int testCase, AsyncKeyEncryptionKey key, APISpec spec) throws InvalidKeyException {
this.testCase = testCase;
this.plainText = spec.getRandomData(DOWNLOAD_SIZE - 2);
EncryptedBlob encryptedBlob = new EncryptedBlobAsyncClient(
null, "https:
.encryptBlob(Flux.just(this.plainText)).block();
this.cipherText = APISpec.collectBytesInBuffer(encryptedBlob.getCiphertextFlux()).block();
this.encryptionData = encryptedBlob.getEncryptionData();
} | null, "https: | public EncryptedFlux(int testCase, AsyncKeyEncryptionKey key, APISpec spec) throws InvalidKeyException {
this.testCase = testCase;
this.plainText = spec.getRandomData(DOWNLOAD_SIZE - 2);
EncryptedBlob encryptedBlob = new EncryptedBlobAsyncClient(
null, "https:
.encryptBlob(Flux.just(this.plainText)).block();
this.cipherText = APISpec.collectBytesInBuffer(encryptedBlob.getCiphertextFlux()).block();
this.encryptionData = encryptedBlob.getEncryptionData();
} | class EncryptedFlux extends Flux<ByteBuffer> {
private ByteBuffer plainText;
private ByteBuffer cipherText;
private int testCase;
private EncryptionData encryptionData;
public static final int DATA_OFFSET = 10;
public static final int DATA_COUNT = 40;
private static final int DOWNLOAD_SIZE = 64;
/*
These constants correspond to the positions above.
ByteBuffer limit() is exclusive, which is why we add one to a limit if that byte is supposed to be included, as in
the case of the last byte of the offsetAdjustment.
*/
private static final int POSITION_ONE = 0;
private static final int POSITION_TWO = DATA_OFFSET / 2;
private static final int POSITION_THREE_POSITION = DATA_OFFSET - 1;
private static final int POSITION_THREE_LIMIT = POSITION_THREE_POSITION + 1;
private static final int POSITION_FOUR_POSITION = DATA_OFFSET;
private static final int POSITION_FOUR_LIMIT = POSITION_FOUR_POSITION + 1;
private static final int POSITION_FIVE = DATA_OFFSET + (DATA_COUNT / 2);
private static final int POSITION_SIX_POSITION = DATA_OFFSET + DATA_COUNT - 1;
private static final int POSITION_SIX_LIMIT = POSITION_SIX_POSITION + 1;
private static final int POSITION_SEVEN_POSITION = DATA_OFFSET + DATA_COUNT;
private static final int POSITION_SEVEN_LIMIT = POSITION_SEVEN_POSITION + 1;
private static final int POSITION_EIGHT = DOWNLOAD_SIZE - 10;
private static final int POSITION_NINE_POSITION = DOWNLOAD_SIZE - 1;
private static final int POSITION_NINE_LIMIT = POSITION_NINE_POSITION + 1;
/*
Test cases. Unfortunately because each case covers multiple combinations, the name of each case cannot provide
much insight into to the pairs being tested, but each is commented with the pairs that it tests. There are a
couple redundancies that are necessary to complete sending the entire data when one combination excludes using other
new combinations.
*/
public static final int CASE_ZERO = 0;
public static final int CASE_ONE = 1;
public static final int CASE_TWO = 2;
public static final int CASE_THREE = 3;
public static final int CASE_FOUR = 4;
public static final int CASE_FIVE = 5;
public static final int CASE_SIX = 6;
public static final int CASE_SEVEN = 7;
public static final int CASE_EIGHT = 8;
public static final int CASE_NINE = 9;
public static final int CASE_TEN = 10;
public static final int CASE_ELEVEN = 11;
public static final int CASE_TWELVE = 12;
public static final int CASE_THIRTEEN = 13;
public static final int CASE_FOURTEEN = 14;
public static final int CASE_FIFTEEN = 15;
public static final int CASE_SIXTEEN = 16;
public static final int CASE_SEVENTEEN = 17;
public static final int CASE_EIGHTEEN = 18;
public static final int CASE_NINETEEN = 19;
public static final int CASE_TWENTY = 20;
public static final int CASE_TWENTY_ONE = 21;
public static final int CASE_TWENTY_TWO = 22;
private void sendBuffs(List<Integer> positionArr, List<Integer> limitArr, Subscriber<? super ByteBuffer> s) {
for (int i = 0; i < positionArr.size(); i++) {
ByteBuffer next = this.cipherText.duplicate();
next.position(positionArr.get(i)).limit(limitArr.get(i));
s.onNext(next);
}
}
@Override
public void subscribe(CoreSubscriber<? super ByteBuffer> s) {
List<Integer> positionArr;
List<Integer> limitArr;
switch (this.testCase) {
case CASE_ZERO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_FOUR_POSITION, POSITION_FIVE,
POSITION_SEVEN_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_THREE_LIMIT, POSITION_FIVE, POSITION_SIX_LIMIT,
POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWO:
/*
Note here and in some cases below, without loss of generality, we use FOUR_LIMIT instead of FIVE for the
range 5/7. This is because if we did strictly 1/4 and 5/7, we would skip the values between the
constants that are set as positions 4 and 5. Using FOUR_LIMIT is equivalent in effect to using FIVE as
POSITION_FIVE is representative of any byte within the range.
*/
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_THREE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FOUR:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SIX:
positionArr = Arrays.asList(POSITION_ONE, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_SEVEN:
positionArr = Collections.singletonList(POSITION_ONE);
limitArr = Collections.singletonList(POSITION_NINE_LIMIT);
break;
case CASE_EIGHT:
case CASE_THIRTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO);
limitArr = Arrays.asList(POSITION_TWO, POSITION_NINE_LIMIT);
break;
case CASE_NINE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_ELEVEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWELVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_FOURTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_FOUR_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_FOUR_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIFTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SIX_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_SIXTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SEVENTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_EIGHTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_NINETEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_TWO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_NINE_LIMIT);
break;
default:
throw new IllegalStateException("Unexpected case number");
}
sendBuffs(positionArr, limitArr, s);
s.onComplete();
}
public ByteBuffer getPlainText() {
return this.plainText;
}
public EncryptionData getEncryptionData() {
return this.encryptionData;
}
} | class EncryptedFlux extends Flux<ByteBuffer> {
private ByteBuffer plainText;
private ByteBuffer cipherText;
private int testCase;
private EncryptionData encryptionData;
public static final int DATA_OFFSET = 10;
public static final int DATA_COUNT = 40;
private static final int DOWNLOAD_SIZE = 64;
/*
These constants correspond to the positions above.
ByteBuffer limit() is exclusive, which is why we add one to a limit if that byte is supposed to be included, as in
the case of the last byte of the offsetAdjustment.
*/
private static final int POSITION_ONE = 0;
private static final int POSITION_TWO = DATA_OFFSET / 2;
private static final int POSITION_THREE_POSITION = DATA_OFFSET - 1;
private static final int POSITION_THREE_LIMIT = POSITION_THREE_POSITION + 1;
private static final int POSITION_FOUR_POSITION = DATA_OFFSET;
private static final int POSITION_FOUR_LIMIT = POSITION_FOUR_POSITION + 1;
private static final int POSITION_FIVE = DATA_OFFSET + (DATA_COUNT / 2);
private static final int POSITION_SIX_POSITION = DATA_OFFSET + DATA_COUNT - 1;
private static final int POSITION_SIX_LIMIT = POSITION_SIX_POSITION + 1;
private static final int POSITION_SEVEN_POSITION = DATA_OFFSET + DATA_COUNT;
private static final int POSITION_SEVEN_LIMIT = POSITION_SEVEN_POSITION + 1;
private static final int POSITION_EIGHT = DOWNLOAD_SIZE - 10;
private static final int POSITION_NINE_POSITION = DOWNLOAD_SIZE - 1;
private static final int POSITION_NINE_LIMIT = POSITION_NINE_POSITION + 1;
/*
Test cases. Unfortunately because each case covers multiple combinations, the name of each case cannot provide
much insight into to the pairs being tested, but each is commented with the pairs that it tests. There are a
couple redundancies that are necessary to complete sending the entire data when one combination excludes using other
new combinations.
*/
public static final int CASE_ZERO = 0;
public static final int CASE_ONE = 1;
public static final int CASE_TWO = 2;
public static final int CASE_THREE = 3;
public static final int CASE_FOUR = 4;
public static final int CASE_FIVE = 5;
public static final int CASE_SIX = 6;
public static final int CASE_SEVEN = 7;
public static final int CASE_EIGHT = 8;
public static final int CASE_NINE = 9;
public static final int CASE_TEN = 10;
public static final int CASE_ELEVEN = 11;
public static final int CASE_TWELVE = 12;
public static final int CASE_THIRTEEN = 13;
public static final int CASE_FOURTEEN = 14;
public static final int CASE_FIFTEEN = 15;
public static final int CASE_SIXTEEN = 16;
public static final int CASE_SEVENTEEN = 17;
public static final int CASE_EIGHTEEN = 18;
public static final int CASE_NINETEEN = 19;
public static final int CASE_TWENTY = 20;
public static final int CASE_TWENTY_ONE = 21;
public static final int CASE_TWENTY_TWO = 22;
private void sendBuffs(List<Integer> positionArr, List<Integer> limitArr, Subscriber<? super ByteBuffer> s) {
for (int i = 0; i < positionArr.size(); i++) {
ByteBuffer next = this.cipherText.duplicate();
next.position(positionArr.get(i)).limit(limitArr.get(i));
s.onNext(next);
}
}
@Override
public void subscribe(CoreSubscriber<? super ByteBuffer> s) {
List<Integer> positionArr;
List<Integer> limitArr;
switch (this.testCase) {
case CASE_ZERO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_FOUR_POSITION, POSITION_FIVE,
POSITION_SEVEN_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_THREE_LIMIT, POSITION_FIVE, POSITION_SIX_LIMIT,
POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWO:
/*
Note here and in some cases below, without loss of generality, we use FOUR_LIMIT instead of FIVE for the
range 5/7. This is because if we did strictly 1/4 and 5/7, we would skip the values between the
constants that are set as positions 4 and 5. Using FOUR_LIMIT is equivalent in effect to using FIVE as
POSITION_FIVE is representative of any byte within the range.
*/
positionArr = Arrays.asList(POSITION_ONE, POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_FOUR_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_THREE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SIX_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FOUR:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SIX:
positionArr = Arrays.asList(POSITION_ONE, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_SEVEN:
positionArr = Collections.singletonList(POSITION_ONE);
limitArr = Collections.singletonList(POSITION_NINE_LIMIT);
break;
case CASE_EIGHT:
case CASE_THIRTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO);
limitArr = Arrays.asList(POSITION_TWO, POSITION_NINE_LIMIT);
break;
case CASE_NINE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_ELEVEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWELVE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_TWO, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_TWO, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_FOURTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_FOUR_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_FOUR_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_FIFTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SIX_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_SIXTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SIX_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_SEVENTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_EIGHTEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_NINETEEN:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_POSITION);
limitArr = Arrays.asList(POSITION_THREE_POSITION, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_SEVEN_LIMIT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_ONE:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT, POSITION_EIGHT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_EIGHT, POSITION_NINE_LIMIT);
break;
case CASE_TWENTY_TWO:
positionArr = Arrays.asList(POSITION_ONE, POSITION_THREE_LIMIT);
limitArr = Arrays.asList(POSITION_THREE_LIMIT, POSITION_NINE_LIMIT);
break;
default:
throw new IllegalStateException("Unexpected case number");
}
sendBuffs(positionArr, limitArr, s);
s.onComplete();
}
public ByteBuffer getPlainText() {
return this.plainText;
}
public EncryptionData getEncryptionData() {
return this.encryptionData;
}
} |
formatting nit: (1) line 234 should have }) and line 235 should only have ) (2) Please remove extra tab spaces from line 236-241.. they should be aligned to ) from line 235 | public void checkForRepeatabilityOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "checkForRepeatabilityOptions");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE).flatMap(
requestResponse -> {
return requestResponse.getRequest().getBody().last();
}
))
.assertNext(bodyBuff -> {
String bodyRequest = new String(bodyBuff.array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
assertTrue(bodyRequest.contains("repeatabilityFirstSent"));
})
.verifyComplete();
} | } | public void checkForRepeatabilityOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "checkForRepeatabilityOptions");
StepVerifier.create(
asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, null, Context.NONE)
.flatMap(requestResponse -> {
return requestResponse.getRequest().getBody().last();
})
).assertNext(bodyBuff -> {
String bodyRequest = new String(bodyBuff.array());
assertTrue(bodyRequest.contains("repeatabilityRequestId"));
assertTrue(bodyRequest.contains("repeatabilityFirstSent"));
})
.verifyComplete();
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} | class SmsAsyncClientTests extends SmsTestBase {
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnableSmsTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsUsingConnectionString");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroup");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE))
.assertNext((Iterable<SmsSendResult> sendResults) -> {
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToGroupWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options))
.assertNext((Response<Iterable<SmsSendResult>> response) -> {
for (SmsSendResult result : response.getValue()) {
assertHappyPath(result);
}
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.assertNext(sendResult -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumberWithOptions");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options))
.assertNext((SmsSendResult sendResult) -> {
assertHappyPath(sendResult);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 401).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToFakePhoneNumber");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, Arrays.asList("+15550000000"), MESSAGE);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendTwoMessages");
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext(firstResult -> {
StepVerifier.create(asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE))
.assertNext((SmsSendResult secondResult) -> {
assertNotEquals(firstResult.getMessageId(), secondResult.getMessageId());
assertHappyPath(firstResult);
assertHappyPath(secondResult);
});
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsToSingleNumber");
String to = null;
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsFromNullNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendSmsFromNullNumber");
String from = null;
Mono<SmsSendResult> response = asyncClient.send(from, TO_PHONE_NUMBER, MESSAGE);
StepVerifier.create(response).verifyError();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} |
Consider creating a static final logger as it's used in multiple places. | public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
} | throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException( | public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
} | class RequestContent {
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size.
*/
public static RequestContent fromFile(Path file, long offset, long length) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
return new FileContent(file, offset, length);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new InputStreamContent(content);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0.
*/
public static RequestContent fromInputStream(InputStream content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new InputStreamContent(content, length);
}
} | class RequestContent {
private static final ClientLogger LOGGER = new ClientLogger(RequestContent.class);
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length(), 8092);
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @param chunkSize The requested size for each read of the path.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size or {@code chunkSize} is less than or equal to 0.
*/
public static RequestContent fromFile(Path file, long offset, long length, int chunkSize) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new FileContent(file, offset, length, chunkSize);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
return fromInputStreamInternal(content, null, 8092);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @param chunkSize The requested size for each {@link InputStream
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0 or {@code chunkSize} is less than or equal to
* 0.
*/
public static RequestContent fromInputStream(InputStream content, long length, int chunkSize) {
return fromInputStreamInternal(content, length, chunkSize);
}
private static RequestContent fromInputStreamInternal(InputStream content, Long length, int chunkSize) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length != null && length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new InputStreamContent(content, length, chunkSize);
}
} |
`serializable` should be non-null too. | public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
} | } | public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
} | class RequestContent {
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
}
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size.
*/
public static RequestContent fromFile(Path file, long offset, long length) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
return new FileContent(file, offset, length);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new InputStreamContent(content);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0.
*/
public static RequestContent fromInputStream(InputStream content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new InputStreamContent(content, length);
}
} | class RequestContent {
private static final ClientLogger LOGGER = new ClientLogger(RequestContent.class);
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
}
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length(), 8092);
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @param chunkSize The requested size for each read of the path.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size or {@code chunkSize} is less than or equal to 0.
*/
public static RequestContent fromFile(Path file, long offset, long length, int chunkSize) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new FileContent(file, offset, length, chunkSize);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
return fromInputStreamInternal(content, null, 8092);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @param chunkSize The requested size for each {@link InputStream
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0 or {@code chunkSize} is less than or equal to
* 0.
*/
public static RequestContent fromInputStream(InputStream content, long length, int chunkSize) {
return fromInputStreamInternal(content, length, chunkSize);
}
private static RequestContent fromInputStreamInternal(InputStream content, Long length, int chunkSize) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length != null && length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new InputStreamContent(content, length, chunkSize);
}
} |
I'd rather leave null handling to the `ObjectSerializer`. For JSON serialization null can be an acceptable serialization value, turning into JSON null, for Avro it could result in an empty byte array. | public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
} | } | public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
} | class RequestContent {
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
}
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size.
*/
public static RequestContent fromFile(Path file, long offset, long length) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
return new FileContent(file, offset, length);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new InputStreamContent(content);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0.
*/
public static RequestContent fromInputStream(InputStream content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new InputStreamContent(content, length);
}
} | class RequestContent {
private static final ClientLogger LOGGER = new ClientLogger(RequestContent.class);
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
}
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length(), 8092);
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @param chunkSize The requested size for each read of the path.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size or {@code chunkSize} is less than or equal to 0.
*/
public static RequestContent fromFile(Path file, long offset, long length, int chunkSize) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new FileContent(file, offset, length, chunkSize);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
return fromInputStreamInternal(content, null, 8092);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @param chunkSize The requested size for each {@link InputStream
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0 or {@code chunkSize} is less than or equal to
* 0.
*/
public static RequestContent fromInputStream(InputStream content, long length, int chunkSize) {
return fromInputStreamInternal(content, length, chunkSize);
}
private static RequestContent fromInputStreamInternal(InputStream content, Long length, int chunkSize) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length != null && length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new InputStreamContent(content, length, chunkSize);
}
} |
Yes, I should do that, before it wasn't done as `RequestContent` was an interface, but now that it is an abstract class that isn't an issue. | public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
} | throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException( | public static RequestContent fromBytes(byte[] bytes, int offset, int length) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > bytes.length) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than 'bytes.length'."));
}
return new ArrayContent(bytes, offset, length);
} | class RequestContent {
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size.
*/
public static RequestContent fromFile(Path file, long offset, long length) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' cannot be negative."));
}
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
return new FileContent(file, offset, length);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new InputStreamContent(content);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0.
*/
public static RequestContent fromInputStream(InputStream content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw new ClientLogger(RequestContent.class).logExceptionAsError(new IllegalArgumentException(
"'length' cannot be less than 0."));
}
return new InputStreamContent(content, length);
}
} | class RequestContent {
private static final ClientLogger LOGGER = new ClientLogger(RequestContent.class);
/**
* Converts the {@link RequestContent} into a {@code Flux<ByteBuffer>} for use in reactive streams.
*
* @return The {@link RequestContent} as a {@code Flux<ByteBuffer>}.
*/
public abstract Flux<ByteBuffer> asFluxByteBuffer();
/**
* Gets the length of the {@link RequestContent} if it is able to be calculated.
* <p>
* If the content length isn't able to be calculated null will be returned.
*
* @return The length of the {@link RequestContent} if it is able to be calculated, otherwise null.
*/
public abstract Long getLength();
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
*/
public static RequestContent fromBytes(byte[] bytes) {
Objects.requireNonNull(bytes, "'bytes' cannot be null.");
return fromBytes(bytes, 0, bytes.length);
}
/**
* Creates a {@link RequestContent} that uses {@code byte[]} as its data.
*
* @param bytes The bytes that will be the {@link RequestContent} data.
* @param offset Offset in the bytes where the data will begin.
* @param length Length of the data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code bytes} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than {@code bytes.length}.
*/
/**
* Creates a {@link RequestContent} that uses {@link String} as its data.
* <p>
* The passed {@link String} is converted using {@link StandardCharsets
* use {@link
*
* @param content The string that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromString(String content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return fromBytes(content.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link RequestContent} that uses {@link BinaryData} as its data.
*
* @param content The {@link BinaryData} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromBinaryData(BinaryData content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new ByteBufferContent(content.toByteBuffer());
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
*/
public static RequestContent fromFile(Path file) {
Objects.requireNonNull(file, "'file' cannot be null.");
return fromFile(file, 0, file.toFile().length(), 8092);
}
/**
* Creates a {@link RequestContent} that uses {@link Path} as its data.
*
* @param file The {@link Path} that will be the {@link RequestContent} data.
* @param offset Offset in the {@link Path} where the data will begin.
* @param length Length of the data.
* @param chunkSize The requested size for each read of the path.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code file} is null.
* @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code
* length} is greater than the file size or {@code chunkSize} is less than or equal to 0.
*/
public static RequestContent fromFile(Path file, long offset, long length, int chunkSize) {
Objects.requireNonNull(file, "'file' cannot be null.");
if (offset < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be negative."));
}
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be negative."));
}
if (offset + length > file.toFile().length()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'offset' plus 'length' cannot be greater than the file's size."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new FileContent(file, offset, length, chunkSize);
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* This uses an {@link ObjectSerializer} found on the classpath.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
*/
public static RequestContent fromObject(Object serializable) {
return fromObject(serializable, JsonSerializerProviders.createInstance(true));
}
/**
* Creates a {@link RequestContent} that uses a serialized {@link Object} as its data.
* <p>
* The {@link RequestContent} returned has a null {@link
* {@link BinaryData
* create the request content.
*
* @param serializable An {@link Object} that will be serialized to be the {@link RequestContent} data.
* @param serializer The {@link ObjectSerializer} that will serialize the {@link Object}.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code serializer} is null.
*/
public static RequestContent fromObject(Object serializable, ObjectSerializer serializer) {
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new SerializableContent(serializable, serializer);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link Flux} of {@link ByteBuffer} as its data.
* <p>
* The {@link RequestContent} created by this factory method doesn't buffer the passed {@link Flux} of {@link
* ByteBuffer}, if the content must be replay-able the passed {@link Flux} of {@link ByteBuffer} must be replay-able
* as well.
*
* @param content The {@link Flux} of {@link ByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
public static RequestContent fromFlux(Flux<ByteBuffer> content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content) {
Objects.requireNonNull(content, "'content' cannot be null.");
return new FluxByteBufferContent(content);
}
/**
* Creates a {@link RequestContent} that uses a {@link BufferedFluxByteBuffer} as its data.
*
* @param content The {@link BufferedFluxByteBuffer} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code content} is null.
* @throws IllegalStateException If {@code length} is less than 0.
*/
static RequestContent fromBufferedFlux(BufferedFluxByteBuffer content, long length) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
return new FluxByteBufferContent(content, length);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
* <p>
* {@link RequestContent
* non-null use {@link RequestContent
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
*/
public static RequestContent fromInputStream(InputStream content) {
return fromInputStreamInternal(content, null, 8092);
}
/**
* Creates a {@link RequestContent} that uses an {@link InputStream} as its data.
*
* @param content The {@link InputStream} that will be the {@link RequestContent} data.
* @param length The length of the content.
* @param chunkSize The requested size for each {@link InputStream
* @return A new {@link RequestContent}.
* @throws NullPointerException If {@code inputStream} is null.
* @throws IllegalArgumentException If {@code length} is less than 0 or {@code chunkSize} is less than or equal to
* 0.
*/
public static RequestContent fromInputStream(InputStream content, long length, int chunkSize) {
return fromInputStreamInternal(content, length, chunkSize);
}
private static RequestContent fromInputStreamInternal(InputStream content, Long length, int chunkSize) {
Objects.requireNonNull(content, "'content' cannot be null.");
if (length != null && length < 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("'length' cannot be less than 0."));
}
if (chunkSize <= 0) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"'chunkSize' cannot be less than or equal to 0."));
}
return new InputStreamContent(content, length, chunkSize);
}
} |
this should be `CountryRegion` | public void beginRecognizeIdentityDocumentsFromUrlWithOptions() {
String licenseDocumentUrl = "licenseDocumentUrl";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl,
new RecognizeIdentityDocumentOptions()
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
} | FormField countryFormField = recognizedFields.get("Country"); | public void beginRecognizeIdentityDocumentsFromUrlWithOptions() {
String licenseDocumentUrl = "licenseDocumentUrl";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl,
new RecognizeIdentityDocumentOptions()
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
} | class FormRecognizerAsyncClientJavaDocCodeSnippets {
private final FormRecognizerAsyncClient formRecognizerAsyncClient
= new FormRecognizerClientBuilder().buildAsyncClient();
/**
* Code snippet for creating a {@link FormRecognizerAsyncClient}
*/
public void createFormRecognizerAsyncClient() {
FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildAsyncClient();
}
/**
* Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline
*/
public void createFormRecognizerAsyncClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildAsyncClient();
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeCustomFormsFromUrl() {
String formUrl = "{form_url}";
String modelId = "{custom_trained_model_id}";
formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeCustomFormsFromUrlWithOptions() {
String formUrl = "{formUrl}";
String modelId = "{model_id}";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomForms() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length())
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomFormsWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(),
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldName, formField) -> {
System.out.printf("Field text: %s%n", fieldName);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeContentFromUrl() {
String formUrl = "{formUrl}";
formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable ->
formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
* options
*/
public void beginRecognizeContentFromUrlWithOptions() {
String formUrl = "{formUrl}";
formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl,
new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable ->
formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContent() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length())
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable ->
formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContentWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(),
new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeReceiptsFromUrl() {
String receiptUrl = "{receiptUrl}";
formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedForm = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeReceiptsFromUrlWithOptions() {
String receiptUrl = "{receiptUrl}";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedReceipt = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceipts() throws IOException {
File receipt = new File("{file_source_url}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath())));
formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedForm = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceiptsWithOptions() throws IOException {
File receipt = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath())));
formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(),
new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedForm = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeBusinessCardsFromUrl() {
String businessCardUrl = "{business_card_url}";
formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedForm = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeBusinessCardsFromUrlWithOptions() {
String businessCardUrl = "{business_card_url}";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCards() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath())));
formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedForm = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCardsWithOptions() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath())));
formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(),
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedForm = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrl() {
String invoiceUrl = "invoice_url";
formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrlWithOptions() {
String invoiceUrl = "invoice_url";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoices() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())));
formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoicesWithOptions() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())));
formRecognizerAsyncClient.beginRecognizeInvoices(buffer,
invoice.length(),
new RecognizeInvoicesOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeIDDocumentFromUrl() {
String idDocumentUrl = "idDocumentUrl";
formRecognizerAsyncClient.beginRecognizeIdentityDocumentsFromUrl(idDocumentUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocuments() throws IOException {
File license = new File("local/file_path/license.jpg");
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(license.toPath())));
formRecognizerAsyncClient.beginRecognizeIdentityDocuments(buffer, license.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocumentsWithOptions() throws IOException {
File licenseDocument = new File("local/file_path/license.jpg");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath())));
formRecognizerAsyncClient.beginRecognizeIdentityDocuments(buffer,
licenseDocument.length(),
new RecognizeIdentityDocumentOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
}
} | class FormRecognizerAsyncClientJavaDocCodeSnippets {
private final FormRecognizerAsyncClient formRecognizerAsyncClient
= new FormRecognizerClientBuilder().buildAsyncClient();
/**
* Code snippet for creating a {@link FormRecognizerAsyncClient}
*/
public void createFormRecognizerAsyncClient() {
FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildAsyncClient();
}
/**
* Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline
*/
public void createFormRecognizerAsyncClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildAsyncClient();
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeCustomFormsFromUrl() {
String formUrl = "{form_url}";
String modelId = "{custom_trained_model_id}";
formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeCustomFormsFromUrlWithOptions() {
String formUrl = "{formUrl}";
String modelId = "{model_id}";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomForms() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length())
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomFormsWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(),
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(recognizedForm -> recognizedForm.getFields()
.forEach((fieldName, formField) -> {
System.out.printf("Field text: %s%n", fieldName);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeContentFromUrl() {
String formUrl = "{formUrl}";
formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable ->
formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
* options
*/
public void beginRecognizeContentFromUrlWithOptions() {
String formUrl = "{formUrl}";
formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl,
new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable ->
formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContent() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length())
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable ->
formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContentWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath())));
formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(),
new RecognizeContentOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.flatMap(Flux::fromIterable)
.subscribe(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell ->
System.out.printf("%s ", recognizedTableCell.getText())));
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeReceiptsFromUrl() {
String receiptUrl = "{receiptUrl}";
formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedForm = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeReceiptsFromUrlWithOptions() {
String receiptUrl = "{receiptUrl}";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedReceipt = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceipts() throws IOException {
File receipt = new File("{file_source_url}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath())));
formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedForm = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceiptsWithOptions() throws IOException {
File receipt = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath())));
formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(),
new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedReceipts -> {
for (int i = 0; i < recognizedReceipts.size(); i++) {
RecognizedForm recognizedForm = recognizedReceipts.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Receipt page %d -----------%n", i);
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeBusinessCardsFromUrl() {
String businessCardUrl = "{business_card_url}";
formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedForm = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeBusinessCardsFromUrlWithOptions() {
String businessCardUrl = "{business_card_url}";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCards() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath())));
formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedForm = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCardsWithOptions() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath())));
formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(),
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedBusinessCards -> {
for (int i = 0; i < recognizedBusinessCards.size(); i++) {
RecognizedForm recognizedForm = recognizedBusinessCards.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized Business Card page %d -----------%n", i);
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrl() {
String invoiceUrl = "invoice_url";
formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrlWithOptions() {
String invoiceUrl = "invoice_url";
boolean includeFieldElements = true;
formRecognizerAsyncClient.beginRecognizeInvoicesFromUrl(invoiceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoices() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())));
formRecognizerAsyncClient.beginRecognizeInvoices(buffer, invoice.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoicesWithOptions() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(invoice.toPath())));
formRecognizerAsyncClient.beginRecognizeInvoices(buffer,
invoice.length(),
new RecognizeInvoicesOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedInvoices -> {
for (int i = 0; i < recognizedInvoices.size(); i++) {
RecognizedForm recognizedForm = recognizedInvoices.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeIDDocumentFromUrl() {
String idDocumentUrl = "idDocumentUrl";
formRecognizerAsyncClient.beginRecognizeIdentityDocumentsFromUrl(idDocumentUrl)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocuments() throws IOException {
File license = new File("local/file_path/license.jpg");
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(license.toPath())));
formRecognizerAsyncClient.beginRecognizeIdentityDocuments(buffer, license.length())
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocumentsWithOptions() throws IOException {
File licenseDocument = new File("local/file_path/license.jpg");
boolean includeFieldElements = true;
Flux<ByteBuffer> buffer =
toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath())));
formRecognizerAsyncClient.beginRecognizeIdentityDocuments(buffer,
licenseDocument.length(),
new RecognizeIdentityDocumentOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements))
.setPollInterval(Duration.ofSeconds(5))
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(recognizedIDDocumentResult -> {
for (int i = 0; i < recognizedIDDocumentResult.size(); i++) {
RecognizedForm recognizedForm = recognizedIDDocumentResult.get(i);
Map<String, FormField> recognizedFields = recognizedForm.getFields();
System.out.printf("----------- Recognized license info for page %d -----------%n", i);
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
}
});
}
} |
same here. Anywhere where u had `Country` triple check that it is now `CountryRegion` | public void beginRecognizeIdentityDocumentsFromUrl() {
String licenseDocumentUrl = "licenseDocumentUrl";
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
} | FormField countryFormField = recognizedFields.get("Country"); | public void beginRecognizeIdentityDocumentsFromUrl() {
String licenseDocumentUrl = "licenseDocumentUrl";
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
} | class FormRecognizerClientJavaDocCodeSnippets {
private final FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient();
/**
* Code snippet for creating a {@link FormRecognizerClient}
*/
public void createFormRecognizerClient() {
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for creating a {@link FormRecognizerClient} with pipeline
*/
public void createFormRecognizerClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrl() {
String formUrl = "{form_url}";
String modelId = "{custom_trained_model_id}";
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrlWithOptions() {
String analyzeFilePath = "{file_source_url}";
String modelId = "{model_id}";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomForms() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomFormsWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(),
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeContentFromUrl() {
String formUrl = "{form_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formUrl)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*/
public void beginRecognizeContentFromUrlWithOptions() {
String formPath = "{file_source_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formPath,
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContent() throws IOException {
File form = new File("{local/file_path/fileName.pdf}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeContent(targetStream, form.length())
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContentWithOptions() throws IOException {
File form = new File("{file_source_url}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(),
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrl() {
String receiptUrl = "{file_source_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrlWithOptions() {
String receiptUrl = "{receipt_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5))
.setFieldElementsIncluded(true), Context.NONE)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceipts() throws IOException {
File receipt = new File("{receipt_url}");
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceiptsWithOptions() throws IOException {
File receipt = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient
.beginRecognizeReceipts(targetStream, receipt.length(),
new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrl() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl)
.getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrlWithOptions() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true), Context.NONE)
.setPollInterval(Duration.ofSeconds(5)).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCards() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
* Context)} with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCardsWithOptions() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream,
businessCard.length(),
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrl() {
String invoiceUrl = "invoice_url";
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrlWithOptions() {
String invoiceUrl = "invoice_url";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoices() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoicesWithOptions() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream,
invoice.length(),
new RecognizeInvoicesOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeIdentityDocumentsFromUrlWithOptions() {
String licenseDocumentUrl = "licenseDocumentUrl";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl,
new RecognizeIdentityDocumentOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocuments() throws IOException {
File license = new File("local/file_path/license.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(license.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream, license.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocumentsWithOptions() throws IOException {
File licenseDocument = new File("local/file_path/license.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream,
licenseDocument.length(),
new RecognizeIdentityDocumentOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
} | class FormRecognizerClientJavaDocCodeSnippets {
private final FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient();
/**
* Code snippet for creating a {@link FormRecognizerClient}
*/
public void createFormRecognizerClient() {
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for creating a {@link FormRecognizerClient} with pipeline
*/
public void createFormRecognizerClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrl() {
String formUrl = "{form_url}";
String modelId = "{custom_trained_model_id}";
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrlWithOptions() {
String analyzeFilePath = "{file_source_url}";
String modelId = "{model_id}";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomForms() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomFormsWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(),
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeContentFromUrl() {
String formUrl = "{form_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formUrl)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*/
public void beginRecognizeContentFromUrlWithOptions() {
String formPath = "{file_source_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formPath,
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContent() throws IOException {
File form = new File("{local/file_path/fileName.pdf}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeContent(targetStream, form.length())
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContentWithOptions() throws IOException {
File form = new File("{file_source_url}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(),
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrl() {
String receiptUrl = "{file_source_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrlWithOptions() {
String receiptUrl = "{receipt_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5))
.setFieldElementsIncluded(true), Context.NONE)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceipts() throws IOException {
File receipt = new File("{receipt_url}");
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceiptsWithOptions() throws IOException {
File receipt = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient
.beginRecognizeReceipts(targetStream, receipt.length(),
new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrl() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl)
.getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrlWithOptions() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true), Context.NONE)
.setPollInterval(Duration.ofSeconds(5)).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCards() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
* Context)} with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCardsWithOptions() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream,
businessCard.length(),
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrl() {
String invoiceUrl = "invoice_url";
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrlWithOptions() {
String invoiceUrl = "invoice_url";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoices() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoicesWithOptions() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream,
invoice.length(),
new RecognizeInvoicesOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeIdentityDocumentsFromUrlWithOptions() {
String licenseDocumentUrl = "licenseDocumentUrl";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl,
new RecognizeIdentityDocumentOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocuments() throws IOException {
File license = new File("local/file_path/license.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(license.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream, license.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocumentsWithOptions() throws IOException {
File licenseDocument = new File("local/file_path/license.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream,
licenseDocument.length(),
new RecognizeIdentityDocumentOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
} |
applies to all samples and tests | public void beginRecognizeIdentityDocumentsFromUrl() {
String licenseDocumentUrl = "licenseDocumentUrl";
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
} | FormField countryFormField = recognizedFields.get("Country"); | public void beginRecognizeIdentityDocumentsFromUrl() {
String licenseDocumentUrl = "licenseDocumentUrl";
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
} | class FormRecognizerClientJavaDocCodeSnippets {
private final FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient();
/**
* Code snippet for creating a {@link FormRecognizerClient}
*/
public void createFormRecognizerClient() {
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for creating a {@link FormRecognizerClient} with pipeline
*/
public void createFormRecognizerClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrl() {
String formUrl = "{form_url}";
String modelId = "{custom_trained_model_id}";
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrlWithOptions() {
String analyzeFilePath = "{file_source_url}";
String modelId = "{model_id}";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomForms() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomFormsWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(),
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeContentFromUrl() {
String formUrl = "{form_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formUrl)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*/
public void beginRecognizeContentFromUrlWithOptions() {
String formPath = "{file_source_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formPath,
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContent() throws IOException {
File form = new File("{local/file_path/fileName.pdf}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeContent(targetStream, form.length())
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContentWithOptions() throws IOException {
File form = new File("{file_source_url}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(),
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrl() {
String receiptUrl = "{file_source_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrlWithOptions() {
String receiptUrl = "{receipt_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5))
.setFieldElementsIncluded(true), Context.NONE)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceipts() throws IOException {
File receipt = new File("{receipt_url}");
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceiptsWithOptions() throws IOException {
File receipt = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient
.beginRecognizeReceipts(targetStream, receipt.length(),
new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrl() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl)
.getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrlWithOptions() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true), Context.NONE)
.setPollInterval(Duration.ofSeconds(5)).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCards() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
* Context)} with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCardsWithOptions() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream,
businessCard.length(),
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrl() {
String invoiceUrl = "invoice_url";
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrlWithOptions() {
String invoiceUrl = "invoice_url";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoices() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoicesWithOptions() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream,
invoice.length(),
new RecognizeInvoicesOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeIdentityDocumentsFromUrlWithOptions() {
String licenseDocumentUrl = "licenseDocumentUrl";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl,
new RecognizeIdentityDocumentOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocuments() throws IOException {
File license = new File("local/file_path/license.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(license.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream, license.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocumentsWithOptions() throws IOException {
File licenseDocument = new File("local/file_path/license.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream,
licenseDocument.length(),
new RecognizeIdentityDocumentOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryFormField = recognizedFields.get("Country");
if (countryFormField != null) {
if (FieldValueType.STRING == countryFormField.getValue().getValueType()) {
String country = countryFormField.getValue().asCountryRegion();
System.out.printf("Country: %s, confidence: %.2f%n",
country, countryFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
} | class FormRecognizerClientJavaDocCodeSnippets {
private final FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient();
/**
* Code snippet for creating a {@link FormRecognizerClient}
*/
public void createFormRecognizerClient() {
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for creating a {@link FormRecognizerClient} with pipeline
*/
public void createFormRecognizerClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrl() {
String formUrl = "{form_url}";
String modelId = "{custom_trained_model_id}";
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeCustomFormsFromUrlWithOptions() {
String analyzeFilePath = "{file_source_url}";
String modelId = "{model_id}";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath,
new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomForms() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeCustomFormsWithOptions() throws IOException {
File form = new File("{local/file_path/fileName.jpg}");
String modelId = "{custom_trained_model_id}";
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(),
new RecognizeCustomFormsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setPollInterval(Duration.ofSeconds(10)), Context.NONE)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> {
System.out.printf("Field text: %s%n", fieldText);
System.out.printf("Field value data text: %s%n", formField.getValueData().getText());
System.out.printf("Confidence score: %.2f%n", formField.getConfidence());
}));
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeContentFromUrl() {
String formUrl = "{form_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formUrl)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*/
public void beginRecognizeContentFromUrlWithOptions() {
String formPath = "{file_source_url}";
formRecognizerClient.beginRecognizeContentFromUrl(formPath,
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContent() throws IOException {
File form = new File("{local/file_path/fileName.pdf}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeContent(targetStream, form.length())
.getFinalResult()
.forEach(formPage -> {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* options.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeContentWithOptions() throws IOException {
File form = new File("{file_source_url}");
byte[] fileContent = Files.readAllBytes(form.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(),
new RecognizeContentOptions()
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
System.out.printf("Page Angle: %s%n", formPage.getTextAngle());
System.out.printf("Page Dimension unit: %s%n", formPage.getUnit());
System.out.println("Recognized Tables: ");
formPage.getTables()
.stream()
.flatMap(formTable -> formTable.getCells().stream())
.forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()));
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrl() {
String receiptUrl = "{file_source_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeReceiptsFromUrlWithOptions() {
String receiptUrl = "{receipt_url}";
formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl,
new RecognizeReceiptsOptions()
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5))
.setFieldElementsIncluded(true), Context.NONE)
.getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceipts() throws IOException {
File receipt = new File("{receipt_url}");
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult()
.forEach(recognizedReceipt -> {
Map<String, FormField> recognizedFields = recognizedReceipt.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
});
}
}
/**
* Code snippet for {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeReceiptsWithOptions() throws IOException {
File receipt = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(receipt.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient
.beginRecognizeReceipts(targetStream, receipt.length(),
new RecognizeReceiptsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements)
.setLocale(FormRecognizerLocale.EN_US)
.setPollInterval(Duration.ofSeconds(5)), Context.NONE)
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField merchantNameField = recognizedFields.get("MerchantName");
if (merchantNameField != null) {
if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) {
String merchantName = merchantNameField.getValue().asString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber");
if (merchantPhoneNumberField != null) {
if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) {
String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber();
System.out.printf("Merchant Phone number: %s, confidence: %.2f%n",
merchantAddress, merchantPhoneNumberField.getConfidence());
}
}
FormField transactionDateField = recognizedFields.get("TransactionDate");
if (transactionDateField != null) {
if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) {
LocalDate transactionDate = transactionDateField.getValue().asDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
FormField receiptItemsField = recognizedFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) {
List<FormField> receiptItems = receiptItemsField.getValue().asList();
receiptItems.stream()
.filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType())
.map(formField -> formField.getValue().asMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Quantity".equals(key)) {
if (FieldValueType.FLOAT == formField.getValue().getValueType()) {
Float quantity = formField.getValue().asFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
}));
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrl() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl)
.getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
*/
public void beginRecognizeBusinessCardsFromUrlWithOptions() {
String businessCardUrl = "{business_card_url}";
formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl,
new RecognizeBusinessCardsOptions()
.setFieldElementsIncluded(true), Context.NONE)
.setPollInterval(Duration.ofSeconds(5)).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCards() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult()
.forEach(recognizedBusinessCard -> {
Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
});
}
}
/**
* Code snippet for
* {@link FormRecognizerClient
* Context)} with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeBusinessCardsWithOptions() throws IOException {
File businessCard = new File("{local/file_path/fileName.jpg}");
boolean includeFieldElements = true;
byte[] fileContent = Files.readAllBytes(businessCard.toPath());
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream,
businessCard.length(),
new RecognizeBusinessCardsOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()) {
Map<String, FormField> recognizedFields = recognizedForm.getFields();
FormField contactNamesFormField = recognizedFields.get("ContactNames");
if (contactNamesFormField != null) {
if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
contactNamesList.stream()
.filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
.map(contactName -> {
System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
return contactName.getValue().asMap();
})
.forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
if ("FirstName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String firstName = contactName.getValue().asString();
System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
firstName, contactName.getConfidence());
}
}
if ("LastName".equals(key)) {
if (FieldValueType.STRING == contactName.getValue().getValueType()) {
String lastName = contactName.getValue().asString();
System.out.printf("\tLast Name: %s, confidence: %.2f%n",
lastName, contactName.getConfidence());
}
}
}));
}
}
FormField jobTitles = recognizedFields.get("JobTitles");
if (jobTitles != null) {
if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
List<FormField> jobTitlesItems = jobTitles.getValue().asList();
jobTitlesItems.forEach(jobTitlesItem -> {
if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
String jobTitle = jobTitlesItem.getValue().asString();
System.out.printf("Job Title: %s, confidence: %.2f%n",
jobTitle, jobTitlesItem.getConfidence());
}
});
}
}
}
}
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrl() {
String invoiceUrl = "invoice_url";
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl)
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeInvoicesFromUrlWithOptions() {
String invoiceUrl = "invoice_url";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl,
new RecognizeInvoicesOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerAsyncClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoices() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream, invoice.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
* options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeInvoicesWithOptions() throws IOException {
File invoice = new File("local/file_path/invoice.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(invoice.toPath()));
formRecognizerClient.beginRecognizeInvoices(inputStream,
invoice.length(),
new RecognizeInvoicesOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField customAddrFormField = recognizedFields.get("CustomerAddress");
if (customAddrFormField != null) {
if (FieldValueType.STRING == customAddrFormField.getValue().getValueType()) {
System.out.printf("Customer Address: %s%n", customAddrFormField.getValue().asString());
}
}
FormField invoiceDateFormField = recognizedFields.get("InvoiceDate");
if (invoiceDateFormField != null) {
if (FieldValueType.DATE == invoiceDateFormField.getValue().getValueType()) {
LocalDate invoiceDate = invoiceDateFormField.getValue().asDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateFormField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*/
/**
* Code snippet for
* {@link FormRecognizerAsyncClient
*/
public void beginRecognizeIdentityDocumentsFromUrlWithOptions() {
String licenseDocumentUrl = "licenseDocumentUrl";
boolean includeFieldElements = true;
formRecognizerClient.beginRecognizeIdentityDocumentsFromUrl(licenseDocumentUrl,
new RecognizeIdentityDocumentOptions()
.setFieldElementsIncluded(includeFieldElements),
Context.NONE).setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for {@link FormRecognizerClient
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocuments() throws IOException {
File license = new File("local/file_path/license.jpg");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(license.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream, license.length())
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
/**
* Code snippet for
* {@link FormRecognizerClient
* with options
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public void beginRecognizeIdentityDocumentsWithOptions() throws IOException {
File licenseDocument = new File("local/file_path/license.jpg");
boolean includeFieldElements = true;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(licenseDocument.toPath()));
formRecognizerClient.beginRecognizeIdentityDocuments(inputStream,
licenseDocument.length(),
new RecognizeIdentityDocumentOptions()
.setContentType(FormContentType.IMAGE_JPEG)
.setFieldElementsIncluded(includeFieldElements),
Context.NONE)
.setPollInterval(Duration.ofSeconds(5))
.getFinalResult()
.stream()
.map(RecognizedForm::getFields)
.forEach(recognizedFields -> {
FormField firstNameField = recognizedFields.get("FirstName");
if (firstNameField != null) {
if (FieldValueType.STRING == firstNameField.getValue().getValueType()) {
String firstName = firstNameField.getValue().asString();
System.out.printf("First Name: %s, confidence: %.2f%n",
firstName, firstNameField.getConfidence());
}
}
FormField lastNameField = recognizedFields.get("LastName");
if (lastNameField != null) {
if (FieldValueType.STRING == lastNameField.getValue().getValueType()) {
String lastName = lastNameField.getValue().asString();
System.out.printf("Last name: %s, confidence: %.2f%n",
lastName, lastNameField.getConfidence());
}
}
FormField countryRegionFormField = recognizedFields.get("CountryRegion");
if (countryRegionFormField != null) {
if (FieldValueType.STRING == countryRegionFormField.getValue().getValueType()) {
String countryRegion = countryRegionFormField.getValue().asCountryRegion();
System.out.printf("Country or region: %s, confidence: %.2f%n",
countryRegion, countryRegionFormField.getConfidence());
}
}
FormField dateOfBirthField = recognizedFields.get("DateOfBirth");
if (dateOfBirthField != null) {
if (FieldValueType.DATE == dateOfBirthField.getValue().getValueType()) {
LocalDate dateOfBirth = dateOfBirthField.getValue().asDate();
System.out.printf("Date of Birth: %s, confidence: %.2f%n",
dateOfBirth, dateOfBirthField.getConfidence());
}
}
FormField dateOfExpirationField = recognizedFields.get("DateOfExpiration");
if (dateOfExpirationField != null) {
if (FieldValueType.DATE == dateOfExpirationField.getValue().getValueType()) {
LocalDate expirationDate = dateOfExpirationField.getValue().asDate();
System.out.printf("Document date of expiration: %s, confidence: %.2f%n",
expirationDate, dateOfExpirationField.getConfidence());
}
}
FormField documentNumberField = recognizedFields.get("DocumentNumber");
if (documentNumberField != null) {
if (FieldValueType.STRING == documentNumberField.getValue().getValueType()) {
String documentNumber = documentNumberField.getValue().asString();
System.out.printf("Document number: %s, confidence: %.2f%n",
documentNumber, documentNumberField.getConfidence());
}
}
});
}
} |
Now that the public exception is renamed to `TableServiceException`, we can remove the fully qualified name here and just use import instead. | public static Throwable mapThrowableToTableServiceException(Throwable throwable) {
if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) {
return toTableServiceException(
(com.azure.data.tables.implementation.models.TableServiceErrorException) throwable);
} else {
return throwable;
}
} | if (throwable instanceof com.azure.data.tables.implementation.models.TableServiceErrorException) { | public static Throwable mapThrowableToTableServiceException(Throwable throwable) {
if (throwable instanceof TableServiceErrorException) {
return toTableServiceException((TableServiceErrorException) throwable);
} else {
return throwable;
}
} | class TableUtils {
private TableUtils() {
throw new UnsupportedOperationException("Cannot instantiate TablesUtils");
}
/**
* Convert an implementation {@link com.azure.data.tables.implementation.models.TableServiceError} to a public
* {@link TableServiceError}. This function maps the service returned
* {@link com.azure.data.tables.implementation.models.TableServiceErrorOdataError inner OData error} and its
* contents to the top level {@link TableServiceError error}.
*
* @param tableServiceError The {@link com.azure.data.tables.implementation.models.TableServiceError} returned by
* the service.
*
* @return The {@link TableServiceError} returned by the SDK.
*/
public static TableServiceError toTableServiceError(
com.azure.data.tables.implementation.models.TableServiceError tableServiceError) {
String errorCode = null;
String errorMessage = null;
if (tableServiceError != null) {
final TableServiceErrorOdataError odataError = tableServiceError.getOdataError();
if (odataError != null) {
errorCode = odataError.getCode();
TableServiceErrorOdataErrorMessage odataErrorMessage = odataError.getMessage();
if (odataErrorMessage != null) {
errorMessage = odataErrorMessage.getValue();
}
}
}
return new TableServiceError(errorCode, errorMessage);
}
/**
* Convert an implementation {@link com.azure.data.tables.implementation.models.TableServiceErrorException} to a a
* public {@link TableServiceException}.
*
* @param exception The {@link com.azure.data.tables.implementation.models.TableServiceErrorException}.
*
* @return The {@link TableServiceException} to be thrown.
*/
public static TableServiceException toTableServiceException(
com.azure.data.tables.implementation.models.TableServiceErrorException exception) {
return new TableServiceException(exception.getMessage(), exception.getResponse(),
toTableServiceError(exception.getValue()));
}
/**
* Maps a {@link Throwable} to {@link TableServiceException} if it's an instance of
* {@link com.azure.data.tables.implementation.models.TableServiceErrorException}, else it returns the original
* throwable.
*
* @param throwable A throwable.
*
* @return A Throwable that is either an instance of {@link TableServiceException} or the original throwable.
*/
} | class TableUtils {
private TableUtils() {
throw new UnsupportedOperationException("Cannot instantiate TablesUtils");
}
/**
* Convert an implementation {@link com.azure.data.tables.implementation.models.TableServiceError} to a public
* {@link TableServiceError}. This function maps the service returned
* {@link com.azure.data.tables.implementation.models.TableServiceErrorOdataError inner OData error} and its
* contents to the top level {@link TableServiceError error}.
*
* @param tableServiceError The {@link com.azure.data.tables.implementation.models.TableServiceError} returned by
* the service.
*
* @return The {@link TableServiceError} returned by the SDK.
*/
public static TableServiceError toTableServiceError(
com.azure.data.tables.implementation.models.TableServiceError tableServiceError) {
String errorCode = null;
String errorMessage = null;
if (tableServiceError != null) {
final TableServiceErrorOdataError odataError = tableServiceError.getOdataError();
if (odataError != null) {
errorCode = odataError.getCode();
TableServiceErrorOdataErrorMessage odataErrorMessage = odataError.getMessage();
if (odataErrorMessage != null) {
errorMessage = odataErrorMessage.getValue();
}
}
}
return new TableServiceError(errorCode, errorMessage);
}
/**
* Convert an implementation {@link TableServiceErrorException} to a public {@link TableServiceException}.
*
* @param exception The {@link TableServiceErrorException}.
*
* @return The {@link TableServiceException} to be thrown.
*/
public static TableServiceException toTableServiceException(TableServiceErrorException exception) {
return new TableServiceException(exception.getMessage(), exception.getResponse(),
toTableServiceError(exception.getValue()));
}
/**
* Map a {@link Throwable} to {@link TableServiceException} if it's an instance of
* {@link TableServiceErrorException}, else it returns the original throwable.
*
* @param throwable A throwable.
*
* @return A Throwable that is either an instance of {@link TableServiceException} or the original throwable.
*/
} |
Why this has been changed? | public void httpRequestTest() throws MalformedURLException {
final HmacAuthenticationPolicy clientPolicy = new HmacAuthenticationPolicy(credential);
final HttpPipeline pipeline = new HttpPipelineBuilder()
.httpClient(new NoOpHttpClient())
.policies(clientPolicy, verifyHeadersPolicy)
.build();
HttpRequest request = new HttpRequest(HttpMethod.GET, new URL("http:
StepVerifier.create(pipeline.send(request))
.verifyError(RuntimeException.class);
} | .verifyError(RuntimeException.class); | public void httpRequestTest() throws MalformedURLException {
final HmacAuthenticationPolicy clientPolicy = new HmacAuthenticationPolicy(credential);
final HttpPipeline pipeline = new HttpPipelineBuilder()
.httpClient(new NoOpHttpClient())
.policies(clientPolicy, verifyHeadersPolicy)
.build();
HttpRequest request = new HttpRequest(HttpMethod.GET, new URL("http:
StepVerifier.create(pipeline.send(request))
.verifyError(RuntimeException.class);
} | class NoOpHttpClient implements HttpClient {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return Mono.empty();
}
} | class NoOpHttpClient implements HttpClient {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return Mono.empty();
}
} |
Oops. It should not be there | public static void main(final String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/Form_1.jpg");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContent(toFluxByteBuffer(targetStream), sourceFile.length());
Mono<List<FormPage>> contentPageResultsMono =
recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED.equals(pollResponse.getStatus())) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(
new RuntimeException(
"Polling completed unsuccessfully with status:" + pollResponse.getStatus()));
}
});
contentPageResultsMono.subscribe(contentPageResults -> {
for (int i = 0; i < contentPageResults.size(); i++) {
final FormPage formPage = contentPageResults.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
formTableCell.getBoundingBox().toString());
});
System.out.println();
}
formPage.getLines().forEach(formLine -> {
if (formLine.getAppearance() != null) {
System.out.printf(
"Line %s consists of %d words and has a text style %s with a confidence score of %.2f.%n",
formLine.getText(), formLine.getWords().size(),
formLine.getAppearance().getStyleName(),
formLine.getAppearance().getStyleConfidence());
}
});
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | public static void main(final String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContent(toFluxByteBuffer(targetStream), sourceFile.length());
Mono<List<FormPage>> contentPageResultsMono =
recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED.equals(pollResponse.getStatus())) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(
new RuntimeException(
"Polling completed unsuccessfully with status:" + pollResponse.getStatus()));
}
});
contentPageResultsMono.subscribe(contentPageResults -> {
for (int i = 0; i < contentPageResults.size(); i++) {
final FormPage formPage = contentPageResults.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
formTableCell.getBoundingBox().toString());
});
System.out.println();
}
for (FormSelectionMark selectionMark : formPage.getSelectionMarks()) {
System.out.printf(
"Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence());
}
formPage.getLines().forEach(formLine -> {
if (formLine.getAppearance() != null) {
System.out.printf(
"Line %s consists of %d words and has a text style %s with a confidence score of %.2f.%n",
formLine.getText(), formLine.getWords().size(),
formLine.getAppearance().getStyleName(),
formLine.getAppearance().getStyleConfidence());
}
});
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeContentAsync {
/**
* 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.
*/
} | class RecognizeContentAsync {
/**
* 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.
*/
} | |
Can we change this for "The initialization parameter [id] cannot be null" ? | public void constructWithNullOrEmptyIdShouldThrow() {
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(null), "Should throw on null id");
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(""), "Should throw on empty id");
} | new UnknownIdentifier(null), "Should throw on null id"); | public void constructWithNullOrEmptyIdShouldThrow() {
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(null), "The initialization parameter [id] cannot be null");
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(""), "The initialization parameter [id] cannot be empty");
} | class UnknownIdentifierTests {
final String id = "some id";
@Test
@Test
public void compareEqualUnknownIdentifiers() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
UnknownIdentifier identifier2 = new UnknownIdentifier(id);
assertTrue(identifier1.equals(identifier1));
assertTrue(identifier1.equals(identifier2));
}
@Test
public void compareWithNonUnknownIdentifier() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
Object identifier2 = new Object();
assertFalse(identifier1.equals(identifier2));
}
@Test
public void constructWithValidId() {
UnknownIdentifier result = new UnknownIdentifier(id);
assertNotNull(result.getId());
assertNotNull(result.hashCode());
}
} | class UnknownIdentifierTests {
final String id = "some id";
@Test
@Test
public void compareEqualUnknownIdentifiers() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
UnknownIdentifier identifier2 = new UnknownIdentifier(id);
assertTrue(identifier1.equals(identifier1));
assertTrue(identifier1.equals(identifier2));
}
@Test
public void compareWithNonUnknownIdentifier() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
Object identifier2 = new Object();
assertFalse(identifier1.equals(identifier2));
}
@Test
public void constructWithValidId() {
UnknownIdentifier result = new UnknownIdentifier(id);
assertNotNull(result.getId());
assertNotNull(result.hashCode());
}
} |
Can we change this for "The initialization parameter [id] cannot be empty"? | public void constructWithNullOrEmptyIdShouldThrow() {
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(null), "Should throw on null id");
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(""), "Should throw on empty id");
} | new UnknownIdentifier(""), "Should throw on empty id"); | public void constructWithNullOrEmptyIdShouldThrow() {
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(null), "The initialization parameter [id] cannot be null");
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(""), "The initialization parameter [id] cannot be empty");
} | class UnknownIdentifierTests {
final String id = "some id";
@Test
@Test
public void compareEqualUnknownIdentifiers() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
UnknownIdentifier identifier2 = new UnknownIdentifier(id);
assertTrue(identifier1.equals(identifier1));
assertTrue(identifier1.equals(identifier2));
}
@Test
public void compareWithNonUnknownIdentifier() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
Object identifier2 = new Object();
assertFalse(identifier1.equals(identifier2));
}
@Test
public void constructWithValidId() {
UnknownIdentifier result = new UnknownIdentifier(id);
assertNotNull(result.getId());
assertNotNull(result.hashCode());
}
} | class UnknownIdentifierTests {
final String id = "some id";
@Test
@Test
public void compareEqualUnknownIdentifiers() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
UnknownIdentifier identifier2 = new UnknownIdentifier(id);
assertTrue(identifier1.equals(identifier1));
assertTrue(identifier1.equals(identifier2));
}
@Test
public void compareWithNonUnknownIdentifier() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
Object identifier2 = new Object();
assertFalse(identifier1.equals(identifier2));
}
@Test
public void constructWithValidId() {
UnknownIdentifier result = new UnknownIdentifier(id);
assertNotNull(result.getId());
assertNotNull(result.hashCode());
}
} |
I'm not 100% sure on the difference between `expectError` vs `verifyError`, but this test is supposed to fail at the `http vs https` check. If you debug the code, it was failing somewhere else. | public void httpRequestTest() throws MalformedURLException {
final HmacAuthenticationPolicy clientPolicy = new HmacAuthenticationPolicy(credential);
final HttpPipeline pipeline = new HttpPipelineBuilder()
.httpClient(new NoOpHttpClient())
.policies(clientPolicy, verifyHeadersPolicy)
.build();
HttpRequest request = new HttpRequest(HttpMethod.GET, new URL("http:
StepVerifier.create(pipeline.send(request))
.verifyError(RuntimeException.class);
} | .verifyError(RuntimeException.class); | public void httpRequestTest() throws MalformedURLException {
final HmacAuthenticationPolicy clientPolicy = new HmacAuthenticationPolicy(credential);
final HttpPipeline pipeline = new HttpPipelineBuilder()
.httpClient(new NoOpHttpClient())
.policies(clientPolicy, verifyHeadersPolicy)
.build();
HttpRequest request = new HttpRequest(HttpMethod.GET, new URL("http:
StepVerifier.create(pipeline.send(request))
.verifyError(RuntimeException.class);
} | class NoOpHttpClient implements HttpClient {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return Mono.empty();
}
} | class NoOpHttpClient implements HttpClient {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return Mono.empty();
}
} |
Yup, changes both in this file and in `CommunicationUserIdentifier` | public void constructWithNullOrEmptyIdShouldThrow() {
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(null), "Should throw on null id");
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(""), "Should throw on empty id");
} | new UnknownIdentifier(null), "Should throw on null id"); | public void constructWithNullOrEmptyIdShouldThrow() {
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(null), "The initialization parameter [id] cannot be null");
assertThrows(IllegalArgumentException.class, () ->
new UnknownIdentifier(""), "The initialization parameter [id] cannot be empty");
} | class UnknownIdentifierTests {
final String id = "some id";
@Test
@Test
public void compareEqualUnknownIdentifiers() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
UnknownIdentifier identifier2 = new UnknownIdentifier(id);
assertTrue(identifier1.equals(identifier1));
assertTrue(identifier1.equals(identifier2));
}
@Test
public void compareWithNonUnknownIdentifier() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
Object identifier2 = new Object();
assertFalse(identifier1.equals(identifier2));
}
@Test
public void constructWithValidId() {
UnknownIdentifier result = new UnknownIdentifier(id);
assertNotNull(result.getId());
assertNotNull(result.hashCode());
}
} | class UnknownIdentifierTests {
final String id = "some id";
@Test
@Test
public void compareEqualUnknownIdentifiers() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
UnknownIdentifier identifier2 = new UnknownIdentifier(id);
assertTrue(identifier1.equals(identifier1));
assertTrue(identifier1.equals(identifier2));
}
@Test
public void compareWithNonUnknownIdentifier() {
UnknownIdentifier identifier1 = new UnknownIdentifier(id);
Object identifier2 = new Object();
assertFalse(identifier1.equals(identifier2));
}
@Test
public void constructWithValidId() {
UnknownIdentifier result = new UnknownIdentifier(id);
assertNotNull(result.getId());
assertNotNull(result.hashCode());
}
} |
(Re)setting `retryPolicy` to `null` should be allowed. | public TableClientBuilder retryPolicy(RetryPolicy retryPolicy) {
if (retryPolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null."));
}
this.retryPolicy = retryPolicy;
return this;
} | throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null.")); | public TableClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
} | class TableClientBuilder {
private static final SerializerAdapter TABLES_SERIALIZER = new TablesJacksonSerializer();
private final ClientLogger logger = new ClientLogger(TableClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private String tableName;
private Configuration configuration;
private TokenCredential tokenCredential;
private HttpClient httpClient;
private String endpoint;
private HttpLogOptions httpLogOptions;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private TablesSharedKeyCredential tablesSharedKeyCredential;
private AzureSasCredential azureSasCredential;
private String sasToken;
private TablesServiceVersion version;
private RetryPolicy retryPolicy = new RetryPolicy();
/**
* Creates a builder instance that is able to configure and construct {@link TableClient} and
* {@link TableAsyncClient} objects.
*/
public TableClientBuilder() {
}
/**
* Creates a {@link TableClient} based on options set in the builder.
*
* @return A {@link TableClient} created from the configurations in this builder.
*
* @throws IllegalArgumentException If {@code tableName} is {@code null} or empty.
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableClient buildClient() {
return new TableClient(buildAsyncClient());
}
/**
* Creates a {@link TableAsyncClient} based on options set in the builder.
*
* @return A {@link TableAsyncClient} created from the configurations in this builder.
*
* @throws IllegalArgumentException If {@code tableName} is {@code null} or empty.
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableAsyncClient buildAsyncClient() {
TablesServiceVersion serviceVersion = version != null ? version : TablesServiceVersion.getLatest();
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
tablesSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, endpoint, retryPolicy,
httpLogOptions, clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger);
return new TableAsyncClient(tableName, pipeline, endpoint, serviceVersion, TABLES_SERIALIZER);
}
/**
* Sets the connection string to connect to the service.
*
* @param connectionString Connection string of the storage or CosmosDB table API account.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code connectionString} isn't a valid connection string.
*/
public TableClientBuilder connectionString(String connectionString) {
if (connectionString == null) {
throw logger.logExceptionAsError(new NullPointerException("'connectionString' cannot be null."));
}
StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger);
StorageEndpoint endpoint = storageConnectionString.getTableEndpoint();
if (endpoint == null || endpoint.getPrimaryUri() == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException(
"'connectionString' missing required settings to derive tables service endpoint."));
}
this.endpoint(endpoint.getPrimaryUri());
StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
this.credential(new TablesSharedKeyCredential(authSettings.getAccount().getName(),
authSettings.getAccount().getAccessKey()));
} else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
this.sasToken(authSettings.getSasToken());
}
return this;
}
/**
* Sets the service endpoint.
*
* @param endpoint The URL of the storage or CosmosDB table API account endpoint.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code endpoint} isn't a valid URL.
*/
public TableClientBuilder endpoint(String endpoint) {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL."));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client. If {@code pipeline} is set, all other settings are
* ignored, aside from {@code endpoint}.
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder pipeline(HttpPipeline pipeline) {
if (this.httpPipeline != null && pipeline == null) {
logger.warning("'pipeline' is being set to 'null' when it was previously configured.");
}
this.httpPipeline = pipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration Configuration store used to retrieve environment configurations.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code sasToken} is empty.
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public TableClientBuilder sasToken(String sasToken) {
if (sasToken == null) {
throw logger.logExceptionAsError(new NullPointerException("'sasToken' cannot be null."));
}
if (sasToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sasToken' cannot be null or empty."));
}
this.sasToken = sasToken;
this.tablesSharedKeyCredential = 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 {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public TableClientBuilder credential(AzureSasCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureSasCredential = credential;
return this;
}
/**
* Sets the {@link TablesSharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential {@link TablesSharedKeyCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public TableClientBuilder credential(TablesSharedKeyCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.tablesSharedKeyCredential = credential;
this.tokenCredential = null;
this.sasToken = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential {@link TokenCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public TableClientBuilder credential(TokenCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.tokenCredential = credential;
this.tablesSharedKeyCredential = null;
this.sasToken = null;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* @param httpClient The {@link HttpClient} to use for requests.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.warning("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the 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
*
* @param logOptions The logging configuration to use when sending and receiving requests to and from the service.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public TableClientBuilder httpLogOptions(HttpLogOptions logOptions) {
if (logOptions == null) {
throw logger.logExceptionAsError(new NullPointerException("'logOptions' cannot be null."));
}
this.httpLogOptions = logOptions;
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 {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public TableClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
if (pipelinePolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipelinePolicy' cannot be null."));
}
if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(pipelinePolicy);
} else {
perRetryPolicies.add(pipelinePolicy);
}
return this;
}
/**
* Sets the {@link TablesServiceVersion} that is used when making API requests.
*
* 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.
*
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version The {@link TablesServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder serviceVersion(TablesServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryPolicy {@link RetryPolicy}.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code retryPolicy} is {@code null}.
*/
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the name of the table.
*
* @param tableName Name of the table.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code tableName} is {@code null} or empty.
*/
public TableClientBuilder tableName(String tableName) {
if (tableName == null) {
throw logger.logExceptionAsError(new NullPointerException("'tableName' cannot be null."));
}
if (tableName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'tableName' cannot be null or empty."));
}
this.tableName = tableName;
return this;
}
} | class TableClientBuilder {
private static final SerializerAdapter TABLES_SERIALIZER = new TablesJacksonSerializer();
private final ClientLogger logger = new ClientLogger(TableClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private String tableName;
private Configuration configuration;
private HttpClient httpClient;
private String endpoint;
private HttpLogOptions httpLogOptions;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private AzureNamedKeyCredential azureNamedKeyCredential;
private AzureSasCredential azureSasCredential;
private String sasToken;
private TableServiceVersion version;
private RetryPolicy retryPolicy;
/**
* Creates a builder instance that is able to configure and construct {@link TableClient} and
* {@link TableAsyncClient} objects.
*/
public TableClientBuilder() {
}
/**
* Creates a {@link TableClient} based on options set in the builder.
*
* @return A {@link TableClient} created from the configurations in this builder.
*
* @throws IllegalArgumentException If {@code tableName} is {@code null} or empty.
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableClient buildClient() {
return new TableClient(buildAsyncClient());
}
/**
* Creates a {@link TableAsyncClient} based on options set in the builder.
*
* @return A {@link TableAsyncClient} created from the configurations in this builder.
*
* @throws IllegalArgumentException If {@code tableName} is {@code null} or empty.
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableAsyncClient buildAsyncClient() {
TableServiceVersion serviceVersion = version != null ? version : TableServiceVersion.getLatest();
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
azureNamedKeyCredential, azureSasCredential, sasToken, endpoint, retryPolicy, httpLogOptions,
clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger);
return new TableAsyncClient(tableName, pipeline, endpoint, serviceVersion, TABLES_SERIALIZER);
}
/**
* Sets the connection string to connect to the service.
*
* @param connectionString Connection string of the storage or CosmosDB table API account.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code connectionString} isn't a valid connection string.
*/
public TableClientBuilder connectionString(String connectionString) {
if (connectionString == null) {
throw logger.logExceptionAsError(new NullPointerException("'connectionString' cannot be null."));
}
StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger);
StorageEndpoint endpoint = storageConnectionString.getTableEndpoint();
if (endpoint == null || endpoint.getPrimaryUri() == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException(
"'connectionString' missing required settings to derive tables service endpoint."));
}
this.endpoint(endpoint.getPrimaryUri());
StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
this.credential(new AzureNamedKeyCredential(authSettings.getAccount().getName(),
authSettings.getAccount().getAccessKey()));
} else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
this.sasToken(authSettings.getSasToken());
}
return this;
}
/**
* Sets the service endpoint.
*
* @param endpoint The URL of the storage or CosmosDB table API account endpoint.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code endpoint} isn't a valid URL.
*/
public TableClientBuilder endpoint(String endpoint) {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL."));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client. If {@code pipeline} is set, all other settings are
* ignored, aside from {@code endpoint}.
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder pipeline(HttpPipeline pipeline) {
this.httpPipeline = pipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration Configuration store used to retrieve environment configurations.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code sasToken} is empty.
* @throws NullPointerException If {@code sasToken} is {@code null}.
*/
public TableClientBuilder sasToken(String sasToken) {
if (sasToken == null) {
throw logger.logExceptionAsError(new NullPointerException("'sasToken' cannot be null."));
}
if (sasToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sasToken' cannot be null or empty."));
}
this.sasToken = sasToken;
this.azureNamedKeyCredential = 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 {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public TableClientBuilder credential(AzureSasCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureSasCredential = credential;
return this;
}
/**
* Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
*
* @param credential {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code credential} is {@code null}.
*/
public TableClientBuilder credential(AzureNamedKeyCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureNamedKeyCredential = credential;
this.sasToken = null;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* @param httpClient The {@link HttpClient} to use for requests.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.warning("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the 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
*
* @param logOptions The logging configuration to use when sending and receiving requests to and from the service.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
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 {@link TableClientBuilder}.
*
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public TableClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
if (pipelinePolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipelinePolicy' cannot be null."));
}
if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(pipelinePolicy);
} else {
perRetryPolicies.add(pipelinePolicy);
}
return this;
}
/**
* Sets the {@link TableServiceVersion} that is used when making API requests.
*
* 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.
*
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version The {@link TableServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder serviceVersion(TableServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the request retry policy for all the requests made through the client.
*
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy {@link RetryPolicy}.
*
* @return The updated {@link TableClientBuilder}.
*/
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
*
* @return The updated {@link TableClientBuilder}.
*/
public TableClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the name of the table.
*
* @param tableName Name of the table.
*
* @return The updated {@link TableClientBuilder}.
*
* @throws IllegalArgumentException If {@code tableName} is {@code null} or empty.
*/
public TableClientBuilder tableName(String tableName) {
if (tableName == null) {
throw logger.logExceptionAsError(new NullPointerException("'tableName' cannot be null."));
}
if (tableName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'tableName' cannot be null or empty."));
}
this.tableName = tableName;
return this;
}
} |
`retryPolicy` can be set to null in which case we'll fall back to default retry policy. | public TableServiceClientBuilder retryPolicy(RetryPolicy retryPolicy) {
if (retryPolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null."));
}
this.retryPolicy = retryPolicy;
return this;
} | throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null.")); | public TableServiceClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
} | class TableServiceClientBuilder {
private final ClientLogger logger = new ClientLogger(TableServiceClientBuilder.class);
private final SerializerAdapter serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions = new HttpLogOptions();
private ClientOptions clientOptions;
private TablesServiceVersion version;
private TokenCredential tokenCredential;
private HttpPipeline httpPipeline;
private TablesSharedKeyCredential tablesSharedKeyCredential;
private AzureSasCredential azureSasCredential;
private String sasToken;
private RetryPolicy retryPolicy = new RetryPolicy();
/**
* Creates a builder instance that is able to configure and construct {@link TableServiceClient} and
* {@link TableServiceAsyncClient} objects.
*/
public TableServiceClientBuilder() {
}
/**
* Creates a {@link TableServiceClient} based on options set in the builder.
*
* @return A {@link TableServiceClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceClient buildClient() {
return new TableServiceClient(buildAsyncClient());
}
/**
* Creates a {@link TableServiceAsyncClient} based on options set in the builder.
*
* @return A {@link TableServiceAsyncClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceAsyncClient buildAsyncClient() {
TablesServiceVersion serviceVersion = version != null ? version : TablesServiceVersion.getLatest();
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
tablesSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, endpoint, retryPolicy,
httpLogOptions, clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger);
return new TableServiceAsyncClient(pipeline, endpoint, serviceVersion, serializerAdapter);
}
/**
* Sets the connection string to connect to the service.
*
* @param connectionString Connection string of the storage or CosmosDB table API account.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code connectionString} isn't a valid connection string.
*/
public TableServiceClientBuilder connectionString(String connectionString) {
if (connectionString == null) {
throw logger.logExceptionAsError(new NullPointerException("'connectionString' cannot be null."));
}
StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger);
StorageEndpoint endpoint = storageConnectionString.getTableEndpoint();
if (endpoint == null || endpoint.getPrimaryUri() == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException(
"'connectionString' missing required settings to derive tables service endpoint."));
}
this.endpoint(endpoint.getPrimaryUri());
StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
this.credential(new TablesSharedKeyCredential(authSettings.getAccount().getName(),
authSettings.getAccount().getAccessKey()));
} else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
this.sasToken(authSettings.getSasToken());
}
return this;
}
/**
* Sets the service endpoint.
*
* @param endpoint The URL of the storage or CosmosDB table API account endpoint.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code endpoint} isn't a valid URL.
*/
public TableServiceClientBuilder endpoint(String endpoint) {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL."));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client. If {@code pipeline} is set, all other settings are
* ignored, aside from {@code endpoint}.
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder pipeline(HttpPipeline pipeline) {
if (this.httpPipeline != null && pipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = pipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration Configuration store used to retrieve environment configurations.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code sasToken} is {@code null}.
*/
public TableServiceClientBuilder sasToken(String sasToken) {
if (sasToken == null) {
throw logger.logExceptionAsError(new NullPointerException("'sasToken' cannot be null."));
}
if (sasToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sasToken' cannot be null or empty."));
}
this.sasToken = sasToken;
this.tablesSharedKeyCredential = 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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(AzureSasCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureSasCredential = credential;
return this;
}
/**
* Sets the {@link TablesSharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential {@link TablesSharedKeyCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(TablesSharedKeyCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.tablesSharedKeyCredential = credential;
this.tokenCredential = null;
this.sasToken = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential {@link TokenCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(TokenCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.tokenCredential = credential;
this.tablesSharedKeyCredential = null;
this.sasToken = null;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* @param httpClient The {@link HttpClient} to use for requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.warning("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the 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
*
* @param logOptions The logging configuration to use when sending and receiving requests to and from the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code logOptions} is {@code null}.
*/
public TableServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) {
if (logOptions == null) {
throw logger.logExceptionAsError(new NullPointerException("'logOptions' cannot be null."));
}
this.httpLogOptions = logOptions;
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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code pipelinePolicy} is {@code null}.
*/
public TableServiceClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
if (pipelinePolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipelinePolicy' cannot be null."));
}
if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(pipelinePolicy);
} else {
perRetryPolicies.add(pipelinePolicy);
}
return this;
}
/**
* Sets the {@link TablesServiceVersion} that is used when making API requests.
*
* 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.
*
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version The {@link TablesServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder serviceVersion(TablesServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryPolicy {@link RetryPolicy}.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code retryPolicy} is {@code null}.
*/
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} | class TableServiceClientBuilder {
private final ClientLogger logger = new ClientLogger(TableServiceClientBuilder.class);
private final SerializerAdapter serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private ClientOptions clientOptions;
private TableServiceVersion version;
private HttpPipeline httpPipeline;
private AzureNamedKeyCredential azureNamedKeyCredential;
private AzureSasCredential azureSasCredential;
private String sasToken;
private RetryPolicy retryPolicy;
/**
* Creates a builder instance that is able to configure and construct {@link TableServiceClient} and
* {@link TableServiceAsyncClient} objects.
*/
public TableServiceClientBuilder() {
}
/**
* Creates a {@link TableServiceClient} based on options set in the builder.
*
* @return A {@link TableServiceClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceClient buildClient() {
return new TableServiceClient(buildAsyncClient());
}
/**
* Creates a {@link TableServiceAsyncClient} based on options set in the builder.
*
* @return A {@link TableServiceAsyncClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceAsyncClient buildAsyncClient() {
TableServiceVersion serviceVersion = version != null ? version : TableServiceVersion.getLatest();
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
azureNamedKeyCredential, azureSasCredential, sasToken, endpoint, retryPolicy, httpLogOptions,
clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger);
return new TableServiceAsyncClient(pipeline, endpoint, serviceVersion, serializerAdapter);
}
/**
* Sets the connection string to connect to the service.
*
* @param connectionString Connection string of the storage or CosmosDB table API account.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code connectionString} isn't a valid connection string.
*/
public TableServiceClientBuilder connectionString(String connectionString) {
if (connectionString == null) {
throw logger.logExceptionAsError(new NullPointerException("'connectionString' cannot be null."));
}
StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger);
StorageEndpoint endpoint = storageConnectionString.getTableEndpoint();
if (endpoint == null || endpoint.getPrimaryUri() == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException(
"'connectionString' missing required settings to derive tables service endpoint."));
}
this.endpoint(endpoint.getPrimaryUri());
StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
this.credential(new AzureNamedKeyCredential(authSettings.getAccount().getName(),
authSettings.getAccount().getAccessKey()));
} else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
this.sasToken(authSettings.getSasToken());
}
return this;
}
/**
* Sets the service endpoint.
*
* @param endpoint The URL of the storage or CosmosDB table API account endpoint.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code endpoint} isn't a valid URL.
*/
public TableServiceClientBuilder endpoint(String endpoint) {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL."));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client. If {@code pipeline} is set, all other settings are
* ignored, aside from {@code endpoint}.
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder pipeline(HttpPipeline pipeline) {
this.httpPipeline = pipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration Configuration store used to retrieve environment configurations.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code sasToken} is {@code null}.
*/
public TableServiceClientBuilder sasToken(String sasToken) {
if (sasToken == null) {
throw logger.logExceptionAsError(new NullPointerException("'sasToken' cannot be null."));
}
if (sasToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sasToken' cannot be null or empty."));
}
this.sasToken = sasToken;
this.azureNamedKeyCredential = 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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(AzureSasCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureSasCredential = credential;
return this;
}
/**
* Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
*
* @param credential {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(AzureNamedKeyCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureNamedKeyCredential = credential;
this.sasToken = null;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* @param httpClient The {@link HttpClient} to use for requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.warning("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the 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
*
* @param logOptions The logging configuration to use when sending and receiving requests to and from the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code pipelinePolicy} is {@code null}.
*/
public TableServiceClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
if (pipelinePolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipelinePolicy' cannot be null."));
}
if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(pipelinePolicy);
} else {
perRetryPolicies.add(pipelinePolicy);
}
return this;
}
/**
* Sets the {@link TableServiceVersion} that is used when making API requests.
*
* 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.
*
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The {@link TableServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder serviceVersion(TableServiceVersion serviceVersion) {
this.version = serviceVersion;
return this;
}
/**
* Sets the request retry policy for all the requests made through the client.
*
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy {@link RetryPolicy}.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} |
We'll do this in #21368. | public TableServiceClientBuilder retryPolicy(RetryPolicy retryPolicy) {
if (retryPolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null."));
}
this.retryPolicy = retryPolicy;
return this;
} | throw logger.logExceptionAsError(new NullPointerException("'retryPolicy' cannot be null.")); | public TableServiceClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
} | class TableServiceClientBuilder {
private final ClientLogger logger = new ClientLogger(TableServiceClientBuilder.class);
private final SerializerAdapter serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions = new HttpLogOptions();
private ClientOptions clientOptions;
private TablesServiceVersion version;
private TokenCredential tokenCredential;
private HttpPipeline httpPipeline;
private TablesSharedKeyCredential tablesSharedKeyCredential;
private AzureSasCredential azureSasCredential;
private String sasToken;
private RetryPolicy retryPolicy = new RetryPolicy();
/**
* Creates a builder instance that is able to configure and construct {@link TableServiceClient} and
* {@link TableServiceAsyncClient} objects.
*/
public TableServiceClientBuilder() {
}
/**
* Creates a {@link TableServiceClient} based on options set in the builder.
*
* @return A {@link TableServiceClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceClient buildClient() {
return new TableServiceClient(buildAsyncClient());
}
/**
* Creates a {@link TableServiceAsyncClient} based on options set in the builder.
*
* @return A {@link TableServiceAsyncClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceAsyncClient buildAsyncClient() {
TablesServiceVersion serviceVersion = version != null ? version : TablesServiceVersion.getLatest();
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
tablesSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, endpoint, retryPolicy,
httpLogOptions, clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger);
return new TableServiceAsyncClient(pipeline, endpoint, serviceVersion, serializerAdapter);
}
/**
* Sets the connection string to connect to the service.
*
* @param connectionString Connection string of the storage or CosmosDB table API account.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code connectionString} isn't a valid connection string.
*/
public TableServiceClientBuilder connectionString(String connectionString) {
if (connectionString == null) {
throw logger.logExceptionAsError(new NullPointerException("'connectionString' cannot be null."));
}
StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger);
StorageEndpoint endpoint = storageConnectionString.getTableEndpoint();
if (endpoint == null || endpoint.getPrimaryUri() == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException(
"'connectionString' missing required settings to derive tables service endpoint."));
}
this.endpoint(endpoint.getPrimaryUri());
StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
this.credential(new TablesSharedKeyCredential(authSettings.getAccount().getName(),
authSettings.getAccount().getAccessKey()));
} else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
this.sasToken(authSettings.getSasToken());
}
return this;
}
/**
* Sets the service endpoint.
*
* @param endpoint The URL of the storage or CosmosDB table API account endpoint.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code endpoint} isn't a valid URL.
*/
public TableServiceClientBuilder endpoint(String endpoint) {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL."));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client. If {@code pipeline} is set, all other settings are
* ignored, aside from {@code endpoint}.
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder pipeline(HttpPipeline pipeline) {
if (this.httpPipeline != null && pipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = pipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration Configuration store used to retrieve environment configurations.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code sasToken} is {@code null}.
*/
public TableServiceClientBuilder sasToken(String sasToken) {
if (sasToken == null) {
throw logger.logExceptionAsError(new NullPointerException("'sasToken' cannot be null."));
}
if (sasToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sasToken' cannot be null or empty."));
}
this.sasToken = sasToken;
this.tablesSharedKeyCredential = 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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(AzureSasCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureSasCredential = credential;
return this;
}
/**
* Sets the {@link TablesSharedKeyCredential} used to authorize requests sent to the service.
*
* @param credential {@link TablesSharedKeyCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(TablesSharedKeyCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.tablesSharedKeyCredential = credential;
this.tokenCredential = null;
this.sasToken = null;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service.
*
* @param credential {@link TokenCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(TokenCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.tokenCredential = credential;
this.tablesSharedKeyCredential = null;
this.sasToken = null;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* @param httpClient The {@link HttpClient} to use for requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.warning("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the 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
*
* @param logOptions The logging configuration to use when sending and receiving requests to and from the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code logOptions} is {@code null}.
*/
public TableServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) {
if (logOptions == null) {
throw logger.logExceptionAsError(new NullPointerException("'logOptions' cannot be null."));
}
this.httpLogOptions = logOptions;
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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code pipelinePolicy} is {@code null}.
*/
public TableServiceClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
if (pipelinePolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipelinePolicy' cannot be null."));
}
if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(pipelinePolicy);
} else {
perRetryPolicies.add(pipelinePolicy);
}
return this;
}
/**
* Sets the {@link TablesServiceVersion} that is used when making API requests.
*
* 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.
*
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version The {@link TablesServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder serviceVersion(TablesServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryPolicy {@link RetryPolicy}.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code retryPolicy} is {@code null}.
*/
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} | class TableServiceClientBuilder {
private final ClientLogger logger = new ClientLogger(TableServiceClientBuilder.class);
private final SerializerAdapter serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private ClientOptions clientOptions;
private TableServiceVersion version;
private HttpPipeline httpPipeline;
private AzureNamedKeyCredential azureNamedKeyCredential;
private AzureSasCredential azureSasCredential;
private String sasToken;
private RetryPolicy retryPolicy;
/**
* Creates a builder instance that is able to configure and construct {@link TableServiceClient} and
* {@link TableServiceAsyncClient} objects.
*/
public TableServiceClientBuilder() {
}
/**
* Creates a {@link TableServiceClient} based on options set in the builder.
*
* @return A {@link TableServiceClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceClient buildClient() {
return new TableServiceClient(buildAsyncClient());
}
/**
* Creates a {@link TableServiceAsyncClient} based on options set in the builder.
*
* @return A {@link TableServiceAsyncClient} created from the configurations in this builder.
*
* @throws IllegalStateException If multiple credentials have been specified.
*/
public TableServiceAsyncClient buildAsyncClient() {
TableServiceVersion serviceVersion = version != null ? version : TableServiceVersion.getLatest();
HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline(
azureNamedKeyCredential, azureSasCredential, sasToken, endpoint, retryPolicy, httpLogOptions,
clientOptions, httpClient, perCallPolicies, perRetryPolicies, configuration, logger);
return new TableServiceAsyncClient(pipeline, endpoint, serviceVersion, serializerAdapter);
}
/**
* Sets the connection string to connect to the service.
*
* @param connectionString Connection string of the storage or CosmosDB table API account.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code connectionString} isn't a valid connection string.
*/
public TableServiceClientBuilder connectionString(String connectionString) {
if (connectionString == null) {
throw logger.logExceptionAsError(new NullPointerException("'connectionString' cannot be null."));
}
StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger);
StorageEndpoint endpoint = storageConnectionString.getTableEndpoint();
if (endpoint == null || endpoint.getPrimaryUri() == null) {
throw logger.logExceptionAsError(
new IllegalArgumentException(
"'connectionString' missing required settings to derive tables service endpoint."));
}
this.endpoint(endpoint.getPrimaryUri());
StorageAuthenticationSettings authSettings = storageConnectionString.getStorageAuthSettings();
if (authSettings.getType() == StorageAuthenticationSettings.Type.ACCOUNT_NAME_KEY) {
this.credential(new AzureNamedKeyCredential(authSettings.getAccount().getName(),
authSettings.getAccount().getAccessKey()));
} else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) {
this.sasToken(authSettings.getSasToken());
}
return this;
}
/**
* Sets the service endpoint.
*
* @param endpoint The URL of the storage or CosmosDB table API account endpoint.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws IllegalArgumentException If {@code endpoint} isn't a valid URL.
*/
public TableServiceClientBuilder endpoint(String endpoint) {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL."));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client. If {@code pipeline} is set, all other settings are
* ignored, aside from {@code endpoint}.
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder pipeline(HttpPipeline pipeline) {
this.httpPipeline = pipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration Configuration store used to retrieve environment configurations.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the SAS token used to authorize requests sent to the service.
*
* @param sasToken The SAS token to use for authenticating requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code sasToken} is {@code null}.
*/
public TableServiceClientBuilder sasToken(String sasToken) {
if (sasToken == null) {
throw logger.logExceptionAsError(new NullPointerException("'sasToken' cannot be null."));
}
if (sasToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sasToken' cannot be null or empty."));
}
this.sasToken = sasToken;
this.azureNamedKeyCredential = 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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(AzureSasCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureSasCredential = credential;
return this;
}
/**
* Sets the {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
*
* @param credential {@link AzureNamedKeyCredential} used to authorize requests sent to the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code credential} is {@code null}.
*/
public TableServiceClientBuilder credential(AzureNamedKeyCredential credential) {
if (credential == null) {
throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null."));
}
this.azureNamedKeyCredential = credential;
this.sasToken = null;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* @param httpClient The {@link HttpClient} to use for requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.warning("'httpClient' is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Sets the 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
*
* @param logOptions The logging configuration to use when sending and receiving requests to and from the service.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
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 {@link TableServiceClientBuilder}.
*
* @throws NullPointerException if {@code pipelinePolicy} is {@code null}.
*/
public TableServiceClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
if (pipelinePolicy == null) {
throw logger.logExceptionAsError(new NullPointerException("'pipelinePolicy' cannot be null."));
}
if (pipelinePolicy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(pipelinePolicy);
} else {
perRetryPolicies.add(pipelinePolicy);
}
return this;
}
/**
* Sets the {@link TableServiceVersion} that is used when making API requests.
*
* 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.
*
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The {@link TableServiceVersion} of the service to be used when making requests.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder serviceVersion(TableServiceVersion serviceVersion) {
this.version = serviceVersion;
return this;
}
/**
* Sets the request retry policy for all the requests made through the client.
*
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy {@link RetryPolicy}.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
/**
* Sets the client options such as application ID and custom headers to set on a request.
*
* @param clientOptions The {@link ClientOptions}.
*
* @return The updated {@link TableServiceClientBuilder}.
*/
public TableServiceClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} |
corrected it | public EncryptionKeyWrapMetadata(String type, String name, String value) {
Preconditions.checkNotNull(type, "type is null");
Preconditions.checkNotNull(value, "value is null");
Preconditions.checkNotNull(name, "value is null");
this.type = type;
this.name = name;
this.value = value;
} | Preconditions.checkNotNull(name, "value is null"); | public EncryptionKeyWrapMetadata(String type, String name, String value) {
Preconditions.checkNotNull(type, "type is null");
Preconditions.checkNotNull(value, "value is null");
Preconditions.checkNotNull(name, "name is null");
this.type = type;
this.name = name;
this.value = value;
} | class EncryptionKeyWrapMetadata {
/**
* For JSON deserialize
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata() {
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param source Existing instance from which to initialize.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata(EncryptionKeyWrapMetadata source) {
this.type = source.type;
this.name = source.name;
this.value = source.value;
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param type Type of the metadata.
* @param name Name of the metadata.
* @param value Value of the metadata.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
@JsonProperty("type")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String type;
@JsonProperty("value")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String value;
@JsonProperty("name")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return value of metadata
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getValue() {
return value;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return name of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getName() {
return name;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return type of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_15_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getType() {
return type;
}
/**
* Returns whether the properties of the passed in key wrap metadata matches with those in the current instance.
*
* @param obj Key wrap metadata to be compared with current instance.
* @return True if the properties of the key wrap metadata passed in matches with those in the current instance, else false.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EncryptionKeyWrapMetadata that = (EncryptionKeyWrapMetadata) obj;
return Objects.equals(type, that.type) &&
Objects.equals(name, that.name) &&
Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(type, name, value);
}
} | class EncryptionKeyWrapMetadata {
/**
* For JSON deserialize
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata() {
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param source Existing instance from which to initialize.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata(EncryptionKeyWrapMetadata source) {
this.type = source.type;
this.name = source.name;
this.value = source.value;
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param type Type of the metadata.
* @param name Name of the metadata.
* @param value Value of the metadata.
*/
@Beta(value = Beta.SinceVersion.V4_16_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
@JsonProperty("type")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String type;
@JsonProperty("value")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String value;
@JsonProperty("name")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return value of metadata
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getValue() {
return value;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return name of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getName() {
return name;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return type of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_16_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getType() {
return type;
}
/**
* Returns whether the properties of the passed in key wrap metadata matches with those in the current instance.
*
* @param obj Key wrap metadata to be compared with current instance.
* @return True if the properties of the key wrap metadata passed in matches with those in the current instance, else false.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EncryptionKeyWrapMetadata that = (EncryptionKeyWrapMetadata) obj;
return Objects.equals(type, that.type) &&
Objects.equals(name, that.name) &&
Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(type, name, value);
}
} |
It might be better to create a github issue for this and add this code there rather than have this code commented out. | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
escapeMapKeys(value);
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<>();
Queue<ObjectNode> target = new LinkedBlockingQueue<>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (!classHasJsonFlatten && !jsonPropertiesWithJsonFlatten.contains(key)) {
continue;
}
if (CHECK_IF_FLATTEN_PROPERTY_PATTERN.matcher(key).matches()) {
String[] values = SPLIT_FLATTEN_PROPERTY_PATTERN.split(key);
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.set(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(key));
resCurrent.remove(key);
outNode = node.get(values[values.length - 1]);
} else if (CHECK_IF_ESCAPED_MAP_PATTERN.matcher(key).matches()) {
String originalKey = REPLACE_ESCAPED_MAP_PATTERN.matcher(key).replaceAll(".");
resCurrent.remove(key);
resCurrent.set(originalKey, outNode);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
} | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
escapeMapKeys(value);
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<>();
Queue<ObjectNode> target = new LinkedBlockingQueue<>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (!classHasJsonFlatten && !jsonPropertiesWithJsonFlatten.contains(key)) {
continue;
}
if (CHECK_IF_FLATTEN_PROPERTY_PATTERN.matcher(key).matches()) {
String[] values = SPLIT_FLATTEN_PROPERTY_PATTERN.split(key);
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.set(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(key));
resCurrent.remove(key);
outNode = node.get(values[values.length - 1]);
} else if (CHECK_IF_ESCAPED_MAP_PATTERN.matcher(key).matches()) {
String originalKey = REPLACE_ESCAPED_MAP_PATTERN.matcher(key).replaceAll(".");
resCurrent.remove(key);
resCurrent.set(originalKey, outNode);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
} | class is annotated with @JsonFlatten add the serializer.
boolean hasJsonFlattenOnClass = beanDesc.getClassAnnotations().has(JsonFlatten.class);
boolean hasJsonFlattenOnProperty = beanDesc.findProperties().stream()
.filter(BeanPropertyDefinition::hasField)
.map(BeanPropertyDefinition::getField)
.anyMatch(field -> field.hasAnnotation(JsonFlatten.class));
if (hasJsonFlattenOnClass || hasJsonFlattenOnProperty) {
return new FlatteningSerializer(beanDesc, serializer, mapper);
} | class is annotated with @JsonFlatten add the serializer.
boolean hasJsonFlattenOnClass = beanDesc.getClassAnnotations().has(JsonFlatten.class);
boolean hasJsonFlattenOnProperty = beanDesc.findProperties().stream()
.filter(BeanPropertyDefinition::hasField)
.map(BeanPropertyDefinition::getField)
.anyMatch(field -> field.hasAnnotation(JsonFlatten.class));
if (hasJsonFlattenOnClass || hasJsonFlattenOnProperty) {
return new FlatteningSerializer(beanDesc, serializer, mapper);
} | |
Yes, I will remove all dead code in the class to have a more in-depth investigation on supporting handling serialization of JsonFlatten classes/fields ourselves. | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
escapeMapKeys(value);
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<>();
Queue<ObjectNode> target = new LinkedBlockingQueue<>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (!classHasJsonFlatten && !jsonPropertiesWithJsonFlatten.contains(key)) {
continue;
}
if (CHECK_IF_FLATTEN_PROPERTY_PATTERN.matcher(key).matches()) {
String[] values = SPLIT_FLATTEN_PROPERTY_PATTERN.split(key);
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.set(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(key));
resCurrent.remove(key);
outNode = node.get(values[values.length - 1]);
} else if (CHECK_IF_ESCAPED_MAP_PATTERN.matcher(key).matches()) {
String originalKey = REPLACE_ESCAPED_MAP_PATTERN.matcher(key).replaceAll(".");
resCurrent.remove(key);
resCurrent.set(originalKey, outNode);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
} | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
escapeMapKeys(value);
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<>();
Queue<ObjectNode> target = new LinkedBlockingQueue<>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (!classHasJsonFlatten && !jsonPropertiesWithJsonFlatten.contains(key)) {
continue;
}
if (CHECK_IF_FLATTEN_PROPERTY_PATTERN.matcher(key).matches()) {
String[] values = SPLIT_FLATTEN_PROPERTY_PATTERN.split(key);
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.set(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(key));
resCurrent.remove(key);
outNode = node.get(values[values.length - 1]);
} else if (CHECK_IF_ESCAPED_MAP_PATTERN.matcher(key).matches()) {
String originalKey = REPLACE_ESCAPED_MAP_PATTERN.matcher(key).replaceAll(".");
resCurrent.remove(key);
resCurrent.set(originalKey, outNode);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
} | class is annotated with @JsonFlatten add the serializer.
boolean hasJsonFlattenOnClass = beanDesc.getClassAnnotations().has(JsonFlatten.class);
boolean hasJsonFlattenOnProperty = beanDesc.findProperties().stream()
.filter(BeanPropertyDefinition::hasField)
.map(BeanPropertyDefinition::getField)
.anyMatch(field -> field.hasAnnotation(JsonFlatten.class));
if (hasJsonFlattenOnClass || hasJsonFlattenOnProperty) {
return new FlatteningSerializer(beanDesc, serializer, mapper);
} | class is annotated with @JsonFlatten add the serializer.
boolean hasJsonFlattenOnClass = beanDesc.getClassAnnotations().has(JsonFlatten.class);
boolean hasJsonFlattenOnProperty = beanDesc.findProperties().stream()
.filter(BeanPropertyDefinition::hasField)
.map(BeanPropertyDefinition::getField)
.anyMatch(field -> field.hasAnnotation(JsonFlatten.class));
if (hasJsonFlattenOnClass || hasJsonFlattenOnProperty) {
return new FlatteningSerializer(beanDesc, serializer, mapper);
} | |
#21505 | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
escapeMapKeys(value);
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<>();
Queue<ObjectNode> target = new LinkedBlockingQueue<>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (!classHasJsonFlatten && !jsonPropertiesWithJsonFlatten.contains(key)) {
continue;
}
if (CHECK_IF_FLATTEN_PROPERTY_PATTERN.matcher(key).matches()) {
String[] values = SPLIT_FLATTEN_PROPERTY_PATTERN.split(key);
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.set(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(key));
resCurrent.remove(key);
outNode = node.get(values[values.length - 1]);
} else if (CHECK_IF_ESCAPED_MAP_PATTERN.matcher(key).matches()) {
String originalKey = REPLACE_ESCAPED_MAP_PATTERN.matcher(key).replaceAll(".");
resCurrent.remove(key);
resCurrent.set(originalKey, outNode);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
} | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
escapeMapKeys(value);
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<>();
Queue<ObjectNode> target = new LinkedBlockingQueue<>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (!classHasJsonFlatten && !jsonPropertiesWithJsonFlatten.contains(key)) {
continue;
}
if (CHECK_IF_FLATTEN_PROPERTY_PATTERN.matcher(key).matches()) {
String[] values = SPLIT_FLATTEN_PROPERTY_PATTERN.split(key);
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.set(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(key));
resCurrent.remove(key);
outNode = node.get(values[values.length - 1]);
} else if (CHECK_IF_ESCAPED_MAP_PATTERN.matcher(key).matches()) {
String originalKey = REPLACE_ESCAPED_MAP_PATTERN.matcher(key).replaceAll(".");
resCurrent.remove(key);
resCurrent.set(originalKey, outNode);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
} | class is annotated with @JsonFlatten add the serializer.
boolean hasJsonFlattenOnClass = beanDesc.getClassAnnotations().has(JsonFlatten.class);
boolean hasJsonFlattenOnProperty = beanDesc.findProperties().stream()
.filter(BeanPropertyDefinition::hasField)
.map(BeanPropertyDefinition::getField)
.anyMatch(field -> field.hasAnnotation(JsonFlatten.class));
if (hasJsonFlattenOnClass || hasJsonFlattenOnProperty) {
return new FlatteningSerializer(beanDesc, serializer, mapper);
} | class is annotated with @JsonFlatten add the serializer.
boolean hasJsonFlattenOnClass = beanDesc.getClassAnnotations().has(JsonFlatten.class);
boolean hasJsonFlattenOnProperty = beanDesc.findProperties().stream()
.filter(BeanPropertyDefinition::hasField)
.map(BeanPropertyDefinition::getField)
.anyMatch(field -> field.hasAnnotation(JsonFlatten.class));
if (hasJsonFlattenOnClass || hasJsonFlattenOnProperty) {
return new FlatteningSerializer(beanDesc, serializer, mapper);
} | |
Incorrect message here - should be `name is null` | public EncryptionKeyWrapMetadata(String type, String name, String value) {
Preconditions.checkNotNull(type, "type is null");
Preconditions.checkNotNull(value, "value is null");
Preconditions.checkNotNull(name, "value is null");
this.type = type;
this.name = name;
this.value = value;
} | Preconditions.checkNotNull(name, "value is null"); | public EncryptionKeyWrapMetadata(String type, String name, String value) {
Preconditions.checkNotNull(type, "type is null");
Preconditions.checkNotNull(value, "value is null");
Preconditions.checkNotNull(name, "name is null");
this.type = type;
this.name = name;
this.value = value;
} | class EncryptionKeyWrapMetadata {
/**
* For JSON deserialize
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata() {
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param source Existing instance from which to initialize.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata(EncryptionKeyWrapMetadata source) {
this.type = source.type;
this.name = source.name;
this.value = source.value;
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param type Type of the metadata.
* @param name Name of the metadata.
* @param value Value of the metadata.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
@JsonProperty("type")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String type;
@JsonProperty("value")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String value;
@JsonProperty("name")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return value of metadata
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getValue() {
return value;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return name of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getName() {
return name;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return type of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_15_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getType() {
return type;
}
/**
* Returns whether the properties of the passed in key wrap metadata matches with those in the current instance.
*
* @param obj Key wrap metadata to be compared with current instance.
* @return True if the properties of the key wrap metadata passed in matches with those in the current instance, else false.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EncryptionKeyWrapMetadata that = (EncryptionKeyWrapMetadata) obj;
return Objects.equals(type, that.type) &&
Objects.equals(name, that.name) &&
Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(type, name, value);
}
} | class EncryptionKeyWrapMetadata {
/**
* For JSON deserialize
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata() {
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param source Existing instance from which to initialize.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public EncryptionKeyWrapMetadata(EncryptionKeyWrapMetadata source) {
this.type = source.type;
this.name = source.name;
this.value = source.value;
}
/**
* Creates a new instance of key wrap metadata based on an existing instance.
*
* @param type Type of the metadata.
* @param name Name of the metadata.
* @param value Value of the metadata.
*/
@Beta(value = Beta.SinceVersion.V4_16_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
@JsonProperty("type")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String type;
@JsonProperty("value")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String value;
@JsonProperty("name")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return value of metadata
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getValue() {
return value;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return name of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_14_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getName() {
return name;
}
/**
* Serialized form of metadata.
* Note: This value is saved in the Cosmos DB service.
* implementors of derived implementations should ensure that this does not have (private) key material or
* credential information.
* @return type of metadata.
*/
@Beta(value = Beta.SinceVersion.V4_16_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING)
public String getType() {
return type;
}
/**
* Returns whether the properties of the passed in key wrap metadata matches with those in the current instance.
*
* @param obj Key wrap metadata to be compared with current instance.
* @return True if the properties of the key wrap metadata passed in matches with those in the current instance, else false.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
EncryptionKeyWrapMetadata that = (EncryptionKeyWrapMetadata) obj;
return Objects.equals(type, that.type) &&
Objects.equals(name, that.name) &&
Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(type, name, value);
}
} |
just a thought, for convenience, we could add a JSON string input Helper class (with a better name than what I wrote), which helps to create the JsonString maybe. | public void groupSendToAllVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("{\"message\": \"Hello world!\"}");
adminGroup.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds,
Context.NONE);
} | adminGroup.sendToAll("{\"message\": \"Hello world!\"}"); | public void groupSendToAllVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("{\"message\": \"Hello world!\"}");
adminGroup.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds,
Context.NONE);
} | class WebPubSubJavaDocCodeSnippets {
public void createAsyncClientConnectionString() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildAsyncClient();
}
public void createSyncClientConnectionString() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildClient();
}
public void createAsyncClientCredentialEndpoint() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.credential(new AzureKeyCredential("<Insert key from Azure Portal>"))
.endpoint("<Insert endpoint from Azure Portal>")
.buildAsyncClient();
}
public void asyncSendToAllVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}").block();
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void asyncSendToAllBytesVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("Hello world!".getBytes()).block();
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void asyncGroupClient() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildAsyncClient();
WebPubSubAsyncGroup adminGroup = client.getAsyncGroup("admins");
}
public void groupAsyncSendToAllVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("{\"message\": \"Hello world!\"}").block();
groupClient.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void groupAsyncSendToAllBytesVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("Hello world!".getBytes()).block();
groupClient.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void groupClient() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildClient();
WebPubSubGroup adminGroup = client.getGroup("admins");
}
public void sendToAllVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}");
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void sendToAllBytesVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("Hello world!".getBytes());
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void groupSendToAllBytesVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("Hello world!".getBytes());
adminGroup.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds,
Context.NONE);
}
private WebPubSubServiceClient getSyncClient() {
return null;
}
private WebPubSubAsyncServiceClient getAsyncClient() {
return null;
}
private List<String> getExcludedUsers() {
return null;
}
private List<String> getExcludedConnectionIds() {
return null;
}
} | class WebPubSubJavaDocCodeSnippets {
public void createAsyncClientConnectionString() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildAsyncClient();
}
public void createSyncClientConnectionString() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildClient();
}
public void createAsyncClientCredentialEndpoint() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.credential(new AzureKeyCredential("<Insert key from Azure Portal>"))
.endpoint("<Insert endpoint from Azure Portal>")
.buildAsyncClient();
}
public void asyncSendToAllVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}").block();
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void asyncSendToAllBytesVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("Hello world!".getBytes()).block();
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void asyncGroupClient() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildAsyncClient();
WebPubSubAsyncGroup adminGroup = client.getAsyncGroup("admins");
}
public void groupAsyncSendToAllVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("{\"message\": \"Hello world!\"}").block();
groupClient.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void groupAsyncSendToAllBytesVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("Hello world!".getBytes()).block();
groupClient.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void groupClient() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildClient();
WebPubSubGroup adminGroup = client.getGroup("admins");
}
public void sendToAllVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}");
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void sendToAllBytesVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("Hello world!".getBytes());
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void groupSendToAllBytesVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("Hello world!".getBytes());
adminGroup.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds,
Context.NONE);
}
private WebPubSubServiceClient getSyncClient() {
return null;
}
private WebPubSubAsyncServiceClient getAsyncClient() {
return null;
}
private List<String> getExcludedUsers() {
return null;
}
private List<String> getExcludedConnectionIds() {
return null;
}
} |
Jackson, Json-P and other libraries already have several helper methods to build the JSON. So, we don't need to roll our own. This also what we do in LLC. | public void groupSendToAllVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("{\"message\": \"Hello world!\"}");
adminGroup.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds,
Context.NONE);
} | adminGroup.sendToAll("{\"message\": \"Hello world!\"}"); | public void groupSendToAllVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("{\"message\": \"Hello world!\"}");
adminGroup.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds,
Context.NONE);
} | class WebPubSubJavaDocCodeSnippets {
public void createAsyncClientConnectionString() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildAsyncClient();
}
public void createSyncClientConnectionString() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildClient();
}
public void createAsyncClientCredentialEndpoint() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.credential(new AzureKeyCredential("<Insert key from Azure Portal>"))
.endpoint("<Insert endpoint from Azure Portal>")
.buildAsyncClient();
}
public void asyncSendToAllVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}").block();
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void asyncSendToAllBytesVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("Hello world!".getBytes()).block();
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void asyncGroupClient() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildAsyncClient();
WebPubSubAsyncGroup adminGroup = client.getAsyncGroup("admins");
}
public void groupAsyncSendToAllVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("{\"message\": \"Hello world!\"}").block();
groupClient.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void groupAsyncSendToAllBytesVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("Hello world!".getBytes()).block();
groupClient.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void groupClient() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildClient();
WebPubSubGroup adminGroup = client.getGroup("admins");
}
public void sendToAllVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}");
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void sendToAllBytesVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("Hello world!".getBytes());
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void groupSendToAllBytesVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("Hello world!".getBytes());
adminGroup.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds,
Context.NONE);
}
private WebPubSubServiceClient getSyncClient() {
return null;
}
private WebPubSubAsyncServiceClient getAsyncClient() {
return null;
}
private List<String> getExcludedUsers() {
return null;
}
private List<String> getExcludedConnectionIds() {
return null;
}
} | class WebPubSubJavaDocCodeSnippets {
public void createAsyncClientConnectionString() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildAsyncClient();
}
public void createSyncClientConnectionString() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.buildClient();
}
public void createAsyncClientCredentialEndpoint() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.credential(new AzureKeyCredential("<Insert key from Azure Portal>"))
.endpoint("<Insert endpoint from Azure Portal>")
.buildAsyncClient();
}
public void asyncSendToAllVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}").block();
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void asyncSendToAllBytesVarArgs() {
WebPubSubAsyncServiceClient client = getAsyncClient();
client.sendToAll("Hello world!".getBytes()).block();
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
client.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void asyncGroupClient() {
WebPubSubAsyncServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildAsyncClient();
WebPubSubAsyncGroup adminGroup = client.getAsyncGroup("admins");
}
public void groupAsyncSendToAllVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("{\"message\": \"Hello world!\"}").block();
groupClient.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN).block();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!",
WebPubSubContentType.TEXT_PLAIN,
excludedConnectionIds).block();
}
public void groupAsyncSendToAllBytesVarArgs() {
WebPubSubAsyncGroup groupClient = null;
groupClient.sendToAll("Hello world!".getBytes()).block();
groupClient.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM).block();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList()).block();
List<String> excludedConnectionIds = getExcludedConnectionIds();
groupClient.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds).block();
}
public void groupClient() {
WebPubSubServiceClient client = new WebPubSubClientBuilder()
.connectionString("<Insert connection string from Azure Portal>")
.hub("chat-portal")
.buildClient();
WebPubSubGroup adminGroup = client.getGroup("admins");
}
public void sendToAllVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("{\"message\": \"Hello world!\"}");
client.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!",
WebPubSubContentType.TEXT_PLAIN,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void sendToAllBytesVarArgs() {
WebPubSubServiceClient client = getSyncClient();
client.sendToAll("Hello world!".getBytes());
client.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
client.sendToAllWithResponse(
"Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Arrays.asList("excluded-connection-id-1", "excluded-connection-id-2"),
Context.NONE);
}
public void groupSendToAllBytesVarArgs() {
WebPubSubGroup adminGroup = null;
adminGroup.sendToAll("Hello world!".getBytes());
adminGroup.sendToAll("Hello world!".getBytes(), WebPubSubContentType.APPLICATION_OCTET_STREAM);
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
Collections.emptyList(),
Context.NONE);
List<String> excludedConnectionIds = getExcludedConnectionIds();
adminGroup.sendToAllWithResponse("Hello world!".getBytes(),
WebPubSubContentType.APPLICATION_OCTET_STREAM,
excludedConnectionIds,
Context.NONE);
}
private WebPubSubServiceClient getSyncClient() {
return null;
}
private WebPubSubAsyncServiceClient getAsyncClient() {
return null;
}
private List<String> getExcludedUsers() {
return null;
}
private List<String> getExcludedConnectionIds() {
return null;
}
} |
typo | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("myalais", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | keystore.engineSetCertificateEntry("myalais", certificate); | public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertTrue(keystore.engineGetCertificateChain(certificateName).length > 0);
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineAliases() {
assertEquals(keystore.engineAliases().nextElement(), certificateName);
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(SYSTEM_PROPERTIES);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
}
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineContainsAlias(certificateName));
keystore.engineDeleteEntry(certificateName);
assertFalse(keystore.engineContainsAlias(certificateName));
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
@Test
public void testRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "true");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
Thread.sleep(10);
assertEquals(ks.getCertificateAlias(certificate), certificateName);
}
@Test
public void testNotRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "false");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
assertNull(ks.getCertificateAlias(certificate));
}
} |
please check if the aliases has more elements first. | public void testEngineAliases() {
assertEquals(keystore.engineAliases().nextElement(), certificateName);
} | assertEquals(keystore.engineAliases().nextElement(), certificateName); | public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("myalais", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertTrue(keystore.engineGetCertificateChain(certificateName).length > 0);
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(SYSTEM_PROPERTIES);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineContainsAlias(certificateName));
keystore.engineDeleteEntry(certificateName);
assertFalse(keystore.engineContainsAlias(certificateName));
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
@Test
public void testRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "true");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
Thread.sleep(10);
assertEquals(ks.getCertificateAlias(certificate), certificateName);
}
@Test
public void testNotRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "false");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
assertNull(ks.getCertificateAlias(certificate));
}
} |
how about assertTrue(keystore.engineAliases().hasMoreElements()); assertEquals(keystore.engineAliases().nextElement(), certificateName); | public void testEngineAliases() {
Enumeration<String> allAliases = keystore.engineAliases();
boolean flag = false;
while (allAliases.hasMoreElements()) {
if (allAliases.nextElement().equals(certificateName)) {
flag = true;
}
}
assertTrue(flag);
} | while (allAliases.hasMoreElements()) { | public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("myalias", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertTrue(keystore.engineGetCertificateChain(certificateName).length > 0);
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(SYSTEM_PROPERTIES);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineContainsAlias(certificateName));
keystore.engineDeleteEntry(certificateName);
assertFalse(keystore.engineContainsAlias(certificateName));
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
@Test
public void testRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "true");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
Thread.sleep(10);
assertEquals(ks.getCertificateAlias(certificate), certificateName);
}
@Test
public void testNotRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "false");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
assertNull(ks.getCertificateAlias(certificate));
}
} |
Thinks. | public void testEngineAliases() {
Enumeration<String> allAliases = keystore.engineAliases();
boolean flag = false;
while (allAliases.hasMoreElements()) {
if (allAliases.nextElement().equals(certificateName)) {
flag = true;
}
}
assertTrue(flag);
} | while (allAliases.hasMoreElements()) { | public void testEngineAliases() {
assertTrue(keystore.engineAliases().hasMoreElements());
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("myalias", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertTrue(keystore.engineGetCertificateChain(certificateName).length > 0);
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineDeleteEntry(certificateName);
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
} | class KeyVaultKeyStoreTest {
/**
* Stores the CER test certificate (which is valid til 2120).
*/
private static final String TEST_CERTIFICATE
= "MIIDeDCCAmCgAwIBAgIQGghBu97rQJKNnUHPWU7xjDANBgkqhkiG9w0BAQsFADAk"
+ "MSIwIAYDVQQDExlodW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMCAXDTIwMDkwMjE3"
+ "NDUyNFoYDzIxMjAwOTAyMTc1NTI0WjAkMSIwIAYDVQQDExlodW5kcmVkLXllYXJz"
+ "LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuU14"
+ "btkN5wmcO2WKXqm1NUKXzi79EtqiFFkrLgPAwj5NNwMw2Akm3GpdEpwkJ8/q3l7d"
+ "frDEVOO9gwZbz7xppyqutjxjllw8CCgjFdfK02btz56CGgh3X25ZZtzPbuMZJM0j"
+ "o4mVEdaFNJ0eUeMppS0DcbbuTWCF7Jf1gvr8GVqx+E0IJUFkE+D4kdTbnJSaeK0A"
+ "KEt94z88MPX18h8ud14uRVmUCYVZrZeswdE2tO1BpazrXELHuXCtrjGxsDDjDzeP"
+ "98aFI9kblkqoJS4TsmloLEjwZLm80cyJDEmpXXMtR7C0FFXFI1BAtIa4mxSgBLsT"
+ "L4GVPEGNANR8COYkHQIDAQABo4GjMIGgMA4GA1UdDwEB/wQEAwIFoDAJBgNVHRME"
+ "AjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAkBgNVHREEHTAbghlo"
+ "dW5kcmVkLXllYXJzLmV4YW1wbGUuY29tMB8GA1UdIwQYMBaAFOGTt4H3ho30O4e+"
+ "hebwJjm2VMvIMB0GA1UdDgQWBBThk7eB94aN9DuHvoXm8CY5tlTLyDANBgkqhkiG"
+ "9w0BAQsFAAOCAQEAGp8mCioVCmM+kZv6r+K2j2uog1k4HBwN1NfRoSsibDB8+QXF"
+ "bmNf3M0imiuR/KJgODyuROwaa/AalxNFMOP8XTL2YmP7XsddBs9ONHHQXKjY/Ojl"
+ "PsIPR7vZjwYPfEB+XEKl2fOIxDQQ921POBV7M6DdTC49T5X+FsLR1AIIfinVetT9"
+ "QmNuvzulBX0T0rea/qpcPK4HTj7ToyImOaf8sXRv2s2ODLUrKWu5hhTNH2l6RIkQ"
+ "U/aIAdQRfDaSE9jhtcVu5d5kCgBs7nz5AzeCisDPo5zIt4Mxej3iVaAJ79oEbHOE"
+ "p192KLXLV/pscA4Wgb+PJ8AAEa5B6xq8p9JO+Q==";
private static KeyVaultKeyStore keystore;
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(SYSTEM_PROPERTIES);
keystore = new KeyVaultKeyStore();
KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
System.getenv("AZURE_KEYVAULT_URI"),
System.getenv("AZURE_KEYVAULT_TENANT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_ID"),
System.getenv("AZURE_KEYVAULT_CLIENT_SECRET"));
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
keystore.engineLoad(parameter);
}
@Test
public void testEngineGetCertificate() {
assertNotNull(keystore.engineGetCertificate(certificateName));
}
@Test
public void testEngineGetCertificateAlias() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificateAlias(certificate));
}
@Test
public void testEngineGetCertificateChain() {
assertNotNull(keystore.engineGetCertificateChain(certificateName));
}
@Test
public void testEngineSetCertificateEntry() {
X509Certificate certificate;
try {
byte[] certificateBytes = Base64.getDecoder().decode(TEST_CERTIFICATE);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate =
(X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
} catch (CertificateException e) {
throw new ProviderException(e);
}
keystore.engineSetCertificateEntry("setcert", certificate);
assertNotNull(keystore.engineGetCertificate("setcert"));
}
@Test
public void testEngineGetKey() {
assertNotNull(keystore.engineGetKey(certificateName, null));
}
@Test
public void testEngineSetKeyEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineSetKeyEntry(certificateName, null, null);
}
@Test
@Test
public void testEngineGetCreationDate() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertNotNull(keystore.engineGetCreationDate(certificateName));
}
@Test
public void testEngineDeleteEntry() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineContainsAlias(certificateName));
keystore.engineDeleteEntry(certificateName);
assertFalse(keystore.engineContainsAlias(certificateName));
}
@Test
public void testEngineSize() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
assertTrue(keystore.engineSize() >= 0);
}
@Test
public void testEngineStore() {
KeyVaultKeyStore keystore = new KeyVaultKeyStore();
keystore.engineStore(null, null);
}
@Test
public void testRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "true");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
Thread.sleep(10);
assertEquals(ks.getCertificateAlias(certificate), certificateName);
}
@Test
public void testNotRefreshEngineGetCertificate() throws Exception {
System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", "false");
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
KeyStore ks = PropertyConvertorUtils.getKeyVaultKeyStore();
Certificate certificate = ks.getCertificate(certificateName);
ks.deleteEntry(certificateName);
assertNull(ks.getCertificateAlias(certificate));
}
} |
This should be printed out only if the error is of type "ClientAuthenticationException". If it is a different exception (like npe/illegal arg/timeout/connection errors), it is not expected. #Resolved | public static void main(String[] args) {
ContainerRegistryAsyncClient anonymousClient = new ContainerRegistryClientBuilder()
.endpoint(ENDPOINT)
.buildAsyncClient();
anonymousClient.deleteRepository(REPOSITORY_NAME).subscribe(deleteRepositoryResult -> {
System.out.println("Unexpected Success: Delete is not allowed on anonymous access");
}, error -> {
System.out.println("Expected exception: Delete is not allowed on anonymous access");
});
} | System.out.println("Expected exception: Delete is not allowed on anonymous access"); | public static void main(String[] args) {
ContainerRegistryAsyncClient anonymousClient = new ContainerRegistryClientBuilder()
.endpoint(ENDPOINT)
.buildAsyncClient();
anonymousClient.deleteRepository(REPOSITORY_NAME).subscribe(deleteRepositoryResult -> {
System.out.println("Unexpected Success: Delete is not allowed on anonymous access");
}, error -> {
System.out.println("Expected exception: Delete is not allowed on anonymous access");
});
} | class AnonymousAsyncClientThrows {
static final String ENDPOINT = "https:
static final String REPOSITORY_NAME = "library/hello-world";
} | class AnonymousAsyncClientThrows {
static final String ENDPOINT = "https:
static final String REPOSITORY_NAME = "library/hello-world";
} |
Why use fail() here but assertEquals in line 119 , 121? | public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | fail("Long Running Operation Status was not successfully completed"); | public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
Why use fail() here but assertEquals in line 119 , 121? | public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | fail("Long Running Operation Status was not successfully completed"); | public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
fail() is the function we use that would just automatically fail the test unconditionally. https://javacodex.com/JUnit/JUnit-Fail-Method | public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | fail("Long Running Operation Status was not successfully completed"); | public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
See above | public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | fail("Long Running Operation Status was not successfully completed"); | public void beginPurchaseandReleasePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberSync", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} | class PhoneNumbersClientIntegrationTest extends PhoneNumbersIntegrationTestBase {
@Override
protected void beforeTest() {
super.beforeTest();
assumeTrue(shouldEnablePhoneNumbersTests());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumber(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithAAD(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PurchasedPhoneNumber number = this.getClientWithManagedIdentity(httpClient, "getPurchasedPhoneNumberWithAADSync").getPurchasedPhoneNumber(phoneNumber);
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getPurchasedPhoneNumberWithResponse(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
Response<PurchasedPhoneNumber> response = this.getClientWithConnectionString(httpClient, "getPurchasedPhoneNumberWithResponseSync")
.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PurchasedPhoneNumber number = response.getValue();
assertEquals(200, response.getStatusCode());
assertEquals(phoneNumber, number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbers(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers(Context.NONE);
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void listPurchasedPhoneNumbersWithoutContext(HttpClient httpClient) {
PagedIterable<PurchasedPhoneNumber> numbers = this.getClientWithConnectionString(httpClient, "listPurchasedPhoneNumbersSync").listPurchasedPhoneNumbers();
PurchasedPhoneNumber number = numbers.iterator().next();
assertNotNull(number.getPhoneNumber());
assertEquals(COUNTRY_CODE, number.getCountryCode());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginSearchAvailablePhoneNumbers(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginSearchAvailablePhoneNumbersSync", true);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
assertEquals(searchResult.getPhoneNumbers().size(), 1);
assertNotNull(searchResult.getSearchId());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
public void beginPurchaseandReleasePhoneNumbersWithoutContext(HttpClient httpClient) {
SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> poller = beginSearchAvailablePhoneNumbersHelper(httpClient, "beginPurchaseandReleasePhoneNumbers_beginSearchAvailablePhoneNumbersWithoutContextSync", false);
PollResponse<PhoneNumberOperation> response = poller.waitForCompletion();
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED == response.getStatus()) {
PhoneNumberSearchResult searchResult = poller.getFinalResult();
String phoneNumber = getTestPhoneNumber(searchResult.getPhoneNumbers().get(0));
PollResponse<PhoneNumberOperation> purchaseOperationResponse = beginPurchasePhoneNumbersHelper(httpClient, searchResult.getSearchId(), "beginPurchasePhoneNumbersWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, purchaseOperationResponse.getStatus());
PollResponse<PhoneNumberOperation> releaseOperationResponse = beginReleasePhoneNumberHelper(httpClient, phoneNumber, "beginReleasePhoneNumberWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, releaseOperationResponse.getStatus());
} else {
fail("Long Running Operation Status was not successfully completed");
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "SKIP_LIVE_TEST",
matches = "(?i)(true)")
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilitiesWithoutContext(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilitiesWithoutContextSync", false).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@DisabledIfEnvironmentVariable(
named = "COMMUNICATION_SKIP_INT_PHONENUMBERS_TEST",
matches = "(?i)(true)")
public void beginUpdatePhoneNumberCapabilities(HttpClient httpClient) {
String phoneNumber = getTestPhoneNumber(PHONE_NUMBER);
PollResponse<PhoneNumberOperation> result = beginUpdatePhoneNumberCapabilitiesHelper(httpClient, phoneNumber, "beginUpdatePhoneNumberCapabilities", true).waitForCompletion();
assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, result.getStatus());
assertEquals(PhoneNumberOperationStatus.SUCCEEDED, result.getValue().getStatus());
}
private SyncPoller<PhoneNumberOperation, PhoneNumberSearchResult> beginSearchAvailablePhoneNumbersHelper(HttpClient httpClient, String testName, boolean withContext) {
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(PhoneNumberCapabilityType.INBOUND_OUTBOUND);
PhoneNumberSearchOptions searchOptions = new PhoneNumberSearchOptions().setQuantity(1);
if (withContext) {
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities,
searchOptions,
Context.NONE));
}
return setPollInterval(getClientWithConnectionString(httpClient, testName).beginSearchAvailablePhoneNumbers(
COUNTRY_CODE,
PhoneNumberType.TOLL_FREE,
PhoneNumberAssignmentType.APPLICATION,
capabilities));
}
private SyncPoller<PhoneNumberOperation, PurchasePhoneNumbersResult> beginPurchasePhoneNumbersHelper(HttpClient httpClient, String searchId, String testName, boolean withContext) {
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginPurchasePhoneNumbers(searchId));
}
private SyncPoller<PhoneNumberOperation, ReleasePhoneNumberResult> beginReleasePhoneNumberHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
if (withContext) {
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber, Context.NONE));
}
return setPollInterval(this.getClientWithConnectionString(httpClient, testName)
.beginReleasePhoneNumber(phoneNumber));
}
private SyncPoller<PhoneNumberOperation, PurchasedPhoneNumber>
beginUpdatePhoneNumberCapabilitiesHelper(HttpClient httpClient, String phoneNumber, String testName, boolean withContext) {
PhoneNumbersClient client = this.getClientWithConnectionString(httpClient, testName);
Response<PurchasedPhoneNumber> responseAcquiredPhone = client.getPurchasedPhoneNumberWithResponse(phoneNumber, Context.NONE);
PhoneNumberCapabilities capabilities = new PhoneNumberCapabilities();
capabilities.setCalling(responseAcquiredPhone.getValue().getCapabilities().getCalling() == PhoneNumberCapabilityType.INBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND);
capabilities.setSms(responseAcquiredPhone.getValue().getCapabilities().getSms() == PhoneNumberCapabilityType.INBOUND_OUTBOUND ? PhoneNumberCapabilityType.OUTBOUND : PhoneNumberCapabilityType.INBOUND_OUTBOUND);
if (withContext) {
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities, Context.NONE));
}
return setPollInterval(client.beginUpdatePhoneNumberCapabilities(phoneNumber, capabilities));
}
private <T, U> SyncPoller<T, U> setPollInterval(SyncPoller<T, U> syncPoller) {
return interceptorManager.isPlaybackMode()
? syncPoller.setPollInterval(Duration.ofMillis(1))
: syncPoller.setPollInterval(Duration.ofSeconds(1));
}
private PhoneNumbersClient getClientWithConnectionString(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private PhoneNumbersClient getClientWithManagedIdentity(HttpClient httpClient, String testName) {
PhoneNumbersClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient);
return addLoggingPolicy(builder, testName).buildClient();
}
private String getTestPhoneNumber(String phoneNumber) {
if (getTestMode() == TestMode.PLAYBACK) {
phoneNumber = "+REDACTED";
}
return phoneNumber;
}
} |
nit: can do the check just once ```java if (context == null) { context = Context.NONE; } ``` | PagedFlux<IncomingRelationship> listIncomingRelationships(String digitalTwinId, Context context) {
return new PagedFlux<>(
() -> listIncomingRelationshipsFirstPageAsync(digitalTwinId, context != null ? context : Context.NONE),
nextLink -> listIncomingRelationshipsNextSinglePageAsync(nextLink, context != null ? context : Context.NONE ));
} | nextLink -> listIncomingRelationshipsNextSinglePageAsync(nextLink, context != null ? context : Context.NONE )); | PagedFlux<IncomingRelationship> listIncomingRelationships(String digitalTwinId, Context context) {
return new PagedFlux<>(
() -> listIncomingRelationshipsFirstPageAsync(digitalTwinId, context != null ? context : Context.NONE),
nextLink -> listIncomingRelationshipsNextSinglePageAsync(nextLink, context != null ? context : Context.NONE ));
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
I tried but the parameter in the lambda expression needs to be final :) | PagedFlux<IncomingRelationship> listIncomingRelationships(String digitalTwinId, Context context) {
return new PagedFlux<>(
() -> listIncomingRelationshipsFirstPageAsync(digitalTwinId, context != null ? context : Context.NONE),
nextLink -> listIncomingRelationshipsNextSinglePageAsync(nextLink, context != null ? context : Context.NONE ));
} | nextLink -> listIncomingRelationshipsNextSinglePageAsync(nextLink, context != null ? context : Context.NONE )); | PagedFlux<IncomingRelationship> listIncomingRelationships(String digitalTwinId, Context context) {
return new PagedFlux<>(
() -> listIncomingRelationshipsFirstPageAsync(digitalTwinId, context != null ? context : Context.NONE),
nextLink -> listIncomingRelationshipsNextSinglePageAsync(nextLink, context != null ? context : Context.NONE ));
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
Should there be any guards on `spanContext` being `null`? | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(), | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} |
Is `SPAN_CONTEXT_KEY` strongly known to exist in the Context? Based on the line of code above it seems like no, so should this use `Optional.orElse(null)` to return `null` if the key doesn't exist instead of throwing a NullPointerException? | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get(); | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} |
hey @alzimmermsft! `extractContext()` above populates `SPAN_CONTEXT_KEY` in the Context. I could add `orElseThrow()` if you think that's better (it's a failure case if it doesn't get populated for some reason). Though it's test code so my initial inclination is not to add guards 😄. Let me know, happy to make updates. | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get(); | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} |
I missed that this was under testing 😃 I agree, let's not add guards here. | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get(); | private static SpanContext getNonRemoteSpanContext(String diagnosticId) {
Context updatedContext = AmqpPropagationFormatUtil.extractContext(diagnosticId, Context.NONE);
SpanContext spanContext = (SpanContext) updatedContext.getData(SPAN_CONTEXT_KEY).get();
return SpanContext.create(spanContext.getTraceId(), spanContext.getSpanId(),
spanContext.getTraceFlags(), spanContext.getTraceState());
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} | class OpenTelemetryHttpPolicyTests {
@Test
public void addAfterPolicyTest() {
final HttpPipeline pipeline = createHttpPipeline();
assertEquals(1, pipeline.getPolicyCount());
assertEquals(OpenTelemetryHttpPolicy.class, pipeline.getPolicy(0).getClass());
}
@Host("https:
@ServiceInterface(name = "TestService")
interface TestService {
@Get("anything")
@ExpectedResponses({200})
HttpBinJSON getAnything(Context context);
}
@Test
public void openTelemetryHttpPolicyTest() {
GlobalOpenTelemetry.resetForTest();
Tracer tracer = OpenTelemetrySdk.builder().build().getTracer("TracerSdkTest");
Span parentSpan = tracer.spanBuilder(PARENT_SPAN_KEY).startSpan();
Scope scope = parentSpan.makeCurrent();
Context tracingContext = new Context(PARENT_SPAN_KEY, parentSpan);
Span expectedSpan = tracer
.spanBuilder("/anything")
.setParent(io.opentelemetry.context.Context.current().with(parentSpan))
.setSpanKind(SpanKind.CLIENT)
.startSpan();
HttpBinJSON response = RestProxy
.create(OpenTelemetryHttpPolicyTests.TestService.class, createHttpPipeline()).getAnything(tracingContext);
String diagnosticId = response.headers().get("Traceparent");
assertNotNull(diagnosticId);
SpanContext returnedSpanContext = getNonRemoteSpanContext(diagnosticId);
verifySpanContextAttributes(expectedSpan.getSpanContext(), returnedSpanContext);
scope.close();
}
private static HttpPipeline createHttpPipeline() {
final HttpClient httpClient = HttpClient.createDefault();
final List<HttpPipelinePolicy> policies = new ArrayList<>();
HttpPolicyProviders.addAfterRetryPolicies(policies);
final HttpPipeline httpPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.build();
return httpPipeline;
}
private static void verifySpanContextAttributes(SpanContext expectedSpanContext, SpanContext actualSpanContext) {
assertEquals(expectedSpanContext.getTraceId(), actualSpanContext.getTraceId());
assertNotEquals(expectedSpanContext.getSpanId(), actualSpanContext.getSpanId());
assertEquals(expectedSpanContext.getTraceFlags(), actualSpanContext.getTraceFlags());
assertEquals(expectedSpanContext.getTraceState(), actualSpanContext.getTraceState());
assertEquals(expectedSpanContext.isValid(), actualSpanContext.isValid());
assertEquals(expectedSpanContext.isRemote(), actualSpanContext.isRemote());
}
/**
* Maps to the JSON return values from http:
*/
static class HttpBinJSON {
@JsonProperty()
private Map<String, String> headers;
/**
* Gets the response headers.
*
* @return The response headers.
*/
public Map<String, String> headers() {
return headers;
}
/**
* Sets the response headers.
*
* @param headers The response headers.
*/
public void headers(Map<String, String> headers) {
this.headers = headers;
}
}
} |
A similar change should be made for Service Bus too. I have created a couple of issues to track this for Event Hubs and Service Bus. https://github.com/Azure/azure-sdk-for-java/issues/21684 https://github.com/Azure/azure-sdk-for-java/issues/21686 | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
String name = span.getName();
if (name.equals("EventHubs.send") || name.equals("EventHubs.message")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
String peerAddress = attributes.get(EVENTHUBS_PEER_ADDRESS);
String destination = attributes.get(EVENTHUBS_MESSAGE_BUS_DESTINATION);
telemetry.setTarget(peerAddress + "/" + destination);
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | } | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
private static final AttributeKey<String> EVENTHUBS_PEER_ADDRESS = AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> EVENTHUBS_MESSAGE_BUS_DESTINATION = AttributeKey.stringKey("message_bus.destination");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} |
Another method should be added to handle Service Bus spans as well. | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
String name = span.getName();
if (name.equals("EventHubs.send") || name.equals("EventHubs.message")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
String peerAddress = attributes.get(EVENTHUBS_PEER_ADDRESS);
String destination = attributes.get(EVENTHUBS_MESSAGE_BUS_DESTINATION);
telemetry.setTarget(peerAddress + "/" + destination);
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | private void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) { | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
private static final AttributeKey<String> EVENTHUBS_PEER_ADDRESS = AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> EVENTHUBS_MESSAGE_BUS_DESTINATION = AttributeKey.stringKey("message_bus.destination");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} |
`ServiceBus.process` is a consumer span and should be request telemetry. Perhaps this should be `ServiceBus.send`? | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
String name = span.getName();
if (name.equals("EventHubs.send") || name.equals("EventHubs.message")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (name.equals("ServiceBus.message") || name.equals("ServiceBus.process")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
telemetry.setTarget(peerAddress + "/" + destination);
}
private void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
telemetry.setTarget(peerAddress + "/" + destination);
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | if (name.equals("ServiceBus.message") || name.equals("ServiceBus.process")) { | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS = AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION = AttributeKey.stringKey("message_bus.destination");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} |
Why EventHubs is `Microsoft.EventHub` and Service Bus is `AZURE SERVICE BUS` ? I belive they are different generations of telemetry types, just wonder if ServiceBus can also move to Azure resource provider namespace | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | telemetry.setType("AZURE SERVICE BUS"); | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} |
ya, i'll raise this with U/X team to support `Microsoft.ServiceBus` 👍 | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | telemetry.setType("AZURE SERVICE BUS"); | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(span, remoteDependencyData);
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), span.getAttributes());
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(SpanData span, RemoteDependencyData remoteDependencyData) {
Attributes attributes = span.getAttributes();
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace != null && azureNamespace.equals("Microsoft.EventHub")) {
applyEventHubsSpan(attributes, remoteDependencyData);
return;
}
if (azureNamespace != null && azureNamespace.equals("Microsoft.ServiceBus")) {
applyServiceBusSpan(attributes, remoteDependencyData);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, span.getKind());
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
telemetry.setType("Http");
telemetry.setTarget(target);
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static void applyEventHubsSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("Microsoft.EventHub");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static void applyServiceBusSpan(Attributes attributes, RemoteDependencyData telemetry) {
telemetry.setType("AZURE SERVICE BUS");
telemetry.setTarget(getAzureSdkTargetSource(attributes));
}
private static String getAzureSdkTargetSource(Attributes attributes) {
String peerAddress = attributes.get(AZURE_SDK_PEER_ADDRESS);
String destination = attributes.get(AZURE_SDK_MESSAGE_BUS_DESTINATION);
return peerAddress + "/" + destination;
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
Attributes attributes = span.getAttributes();
requestData.setSource(getSource(attributes));
if (isAzureQueue(attributes)) {
Long enqueuedTime = attributes.get(AZURE_SDK_ENQUEUED_TIME);
if (enqueuedTime != null) {
long timeSinceEnqueued =
NANOSECONDS.toMillis(span.getStartEpochNanos()) - SECONDS.toMillis(enqueuedTime);
if (timeSinceEnqueued < 0) {
timeSinceEnqueued = 0;
}
if (requestData.getMeasurements() == null) {
requestData.setMeasurements(new HashMap<>());
}
requestData.getMeasurements().put("timeSinceEnqueued", (double) timeSinceEnqueued);
}
}
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String getSource(Attributes attributes) {
if (isAzureQueue(attributes)) {
return getAzureSdkTargetSource(attributes);
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
String source =
nullAwareConcat(
getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")),
"/");
if (source != null) {
return source;
}
return messagingSystem;
}
return null;
}
private static boolean isAzureQueue(Attributes attributes) {
String azureNamespace = attributes.get(AZURE_NAMESPACE);
if (azureNamespace == null) {
return false;
}
return azureNamespace.equals("Microsoft.EventHub") || azureNamespace.equals("Microsoft.ServiceBus");
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (stringKey.equals(AZURE_SDK_MESSAGE_BUS_DESTINATION.getKey())
|| stringKey.equals("az.namespace")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AZURE_NAMESPACE =
AttributeKey.stringKey("az.namespace");
private static final AttributeKey<String> AZURE_SDK_PEER_ADDRESS =
AttributeKey.stringKey("peer.address");
private static final AttributeKey<String> AZURE_SDK_MESSAGE_BUS_DESTINATION =
AttributeKey.stringKey("message_bus.destination");
private static final AttributeKey<Long> AZURE_SDK_ENQUEUED_TIME =
AttributeKey.longKey("x-opt-enqueued-time");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} |
we should remove this validation. service makes sure data is pulled from right place implicitly if extra attributes are requested. there's no need for us validating this. | public ShareListFilesAndDirectoriesOptions setIncludeExtendedInfo(Boolean includeExtendedInfo) {
if (includeTimestamps || includeETag || includeAttributes || includePermissionKey) {
throw logger.logExceptionAsError(
new IllegalStateException("includeExtendedInfo must be true in the current state."));
}
this.includeExtendedInfo = includeExtendedInfo;
return this;
} | } | public ShareListFilesAndDirectoriesOptions setIncludeExtendedInfo(Boolean includeExtendedInfo) {
if (includeTimestamps || includeETag || includeAttributes || includePermissionKey) {
throw logger.logExceptionAsError(
new IllegalStateException("includeExtendedInfo must be true in the current state."));
}
this.includeExtendedInfo = includeExtendedInfo;
return this;
} | class ShareListFilesAndDirectoriesOptions {
private final ClientLogger logger = new ClientLogger(ShareListFilesAndDirectoriesOptions.class);
private String prefix;
private Integer maxResultsPerPage;
private boolean includeTimestamps;
private boolean includeETag;
private boolean includeAttributes;
private boolean includePermissionKey;
private Boolean includeExtendedInfo;
/**
* @return prefix for this listing operation.
*/
public String getPrefix() {
return prefix;
}
/**
* Sets the prefix for a listing operation.
*
* @param prefix the prefix.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
/**
* @return max results per page for this listing operation.
*/
public Integer getMaxResultsPerPage() {
return maxResultsPerPage;
}
/**
* Sets the max results per page for a listing operation.
*
* @param maxResultsPerPage the max results per page.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setMaxResultsPerPage(Integer maxResultsPerPage) {
this.maxResultsPerPage = maxResultsPerPage;
return this;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false while any of these options are true will be unsuccessful.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @return whether to include extended info on this listing operation.
*/
public Boolean includeExtendedInfo() {
return includeExtendedInfo;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false will be unsuccessful.
*
* Sets the prefix for a listing operation.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @param includeExtendedInfo whether to include extended info.
* @return updated options.
* @throws IllegalStateException Throws when attempting to set null when other parameters require it to be true.
*/
/**
* @return whether to include timestamps on this listing operation.
*/
public boolean includeTimestamps() {
return includeTimestamps;
}
/**
* @param includeTimestamps whether to include timestamps on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeTimestamps(boolean includeTimestamps) {
this.includeTimestamps = includeTimestamps;
if (includeTimestamps) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include the etag on this listing operation.
*/
public boolean includeETag() {
return includeETag;
}
/**
* @param includeETag whether to include the etag on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeETag(boolean includeETag) {
this.includeETag = includeETag;
if (includeETag) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include file attributes on this listing operation.
*/
public boolean includeAttributes() {
return includeAttributes;
}
/**
* @param includeAttributes whether to include file attributes on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeAttributes(boolean includeAttributes) {
this.includeAttributes = includeAttributes;
if (includeAttributes) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include the permission key on this listing operation.
*/
public boolean includePermissionKey() {
return includePermissionKey;
}
/**
* @param includePermissionKey whether to include the permission key on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludePermissionKey(boolean includePermissionKey) {
this.includePermissionKey = includePermissionKey;
if (includePermissionKey) {
this.includeExtendedInfo = true;
}
return this;
}
} | class ShareListFilesAndDirectoriesOptions {
private final ClientLogger logger = new ClientLogger(ShareListFilesAndDirectoriesOptions.class);
private String prefix;
private Integer maxResultsPerPage;
private boolean includeTimestamps;
private boolean includeETag;
private boolean includeAttributes;
private boolean includePermissionKey;
private Boolean includeExtendedInfo;
/**
* @return prefix for this listing operation.
*/
public String getPrefix() {
return prefix;
}
/**
* Sets the prefix for a listing operation.
*
* @param prefix the prefix.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
/**
* @return max results per page for this listing operation.
*/
public Integer getMaxResultsPerPage() {
return maxResultsPerPage;
}
/**
* Sets the max results per page for a listing operation.
*
* @param maxResultsPerPage the max results per page.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setMaxResultsPerPage(Integer maxResultsPerPage) {
this.maxResultsPerPage = maxResultsPerPage;
return this;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false while any of these options are true will be unsuccessful.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @return whether to include extended info on this listing operation.
*/
public Boolean includeExtendedInfo() {
return includeExtendedInfo;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false will be unsuccessful.
*
* Sets the prefix for a listing operation.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @param includeExtendedInfo whether to include extended info.
* @return updated options.
* @throws IllegalStateException Throws when attempting to set null when other parameters require it to be true.
*/
/**
* @return whether to include timestamps on this listing operation.
*/
public boolean includeTimestamps() {
return includeTimestamps;
}
/**
* @param includeTimestamps whether to include timestamps on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeTimestamps(boolean includeTimestamps) {
this.includeTimestamps = includeTimestamps;
if (includeTimestamps) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include the etag on this listing operation.
*/
public boolean includeETag() {
return includeETag;
}
/**
* @param includeETag whether to include the etag on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeETag(boolean includeETag) {
this.includeETag = includeETag;
if (includeETag) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include file attributes on this listing operation.
*/
public boolean includeAttributes() {
return includeAttributes;
}
/**
* @param includeAttributes whether to include file attributes on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeAttributes(boolean includeAttributes) {
this.includeAttributes = includeAttributes;
if (includeAttributes) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include the permission key on this listing operation.
*/
public boolean includePermissionKey() {
return includePermissionKey;
}
/**
* @param includePermissionKey whether to include the permission key on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludePermissionKey(boolean includePermissionKey) {
this.includePermissionKey = includePermissionKey;
if (includePermissionKey) {
this.includeExtendedInfo = true;
}
return this;
}
} |
This isn't necessary as well. service will do the right thing. Please remove this and similar logic. | public ShareListFilesAndDirectoriesOptions setIncludeTimestamps(boolean includeTimestamps) {
this.includeTimestamps = includeTimestamps;
if (includeTimestamps) {
this.includeExtendedInfo = true;
}
return this;
} | } | public ShareListFilesAndDirectoriesOptions setIncludeTimestamps(boolean includeTimestamps) {
this.includeTimestamps = includeTimestamps;
if (includeTimestamps) {
this.includeExtendedInfo = true;
}
return this;
} | class ShareListFilesAndDirectoriesOptions {
private final ClientLogger logger = new ClientLogger(ShareListFilesAndDirectoriesOptions.class);
private String prefix;
private Integer maxResultsPerPage;
private boolean includeTimestamps;
private boolean includeETag;
private boolean includeAttributes;
private boolean includePermissionKey;
private Boolean includeExtendedInfo;
/**
* @return prefix for this listing operation.
*/
public String getPrefix() {
return prefix;
}
/**
* Sets the prefix for a listing operation.
*
* @param prefix the prefix.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
/**
* @return max results per page for this listing operation.
*/
public Integer getMaxResultsPerPage() {
return maxResultsPerPage;
}
/**
* Sets the max results per page for a listing operation.
*
* @param maxResultsPerPage the max results per page.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setMaxResultsPerPage(Integer maxResultsPerPage) {
this.maxResultsPerPage = maxResultsPerPage;
return this;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false while any of these options are true will be unsuccessful.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @return whether to include extended info on this listing operation.
*/
public Boolean includeExtendedInfo() {
return includeExtendedInfo;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false will be unsuccessful.
*
* Sets the prefix for a listing operation.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @param includeExtendedInfo whether to include extended info.
* @return updated options.
* @throws IllegalStateException Throws when attempting to set null when other parameters require it to be true.
*/
public ShareListFilesAndDirectoriesOptions setIncludeExtendedInfo(Boolean includeExtendedInfo) {
if (includeTimestamps || includeETag || includeAttributes || includePermissionKey) {
throw logger.logExceptionAsError(
new IllegalStateException("includeExtendedInfo must be true in the current state."));
}
this.includeExtendedInfo = includeExtendedInfo;
return this;
}
/**
* @return whether to include timestamps on this listing operation.
*/
public boolean includeTimestamps() {
return includeTimestamps;
}
/**
* @param includeTimestamps whether to include timestamps on this listing operation.
* @return updated options
*/
/**
* @return whether to include the etag on this listing operation.
*/
public boolean includeETag() {
return includeETag;
}
/**
* @param includeETag whether to include the etag on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeETag(boolean includeETag) {
this.includeETag = includeETag;
if (includeETag) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include file attributes on this listing operation.
*/
public boolean includeAttributes() {
return includeAttributes;
}
/**
* @param includeAttributes whether to include file attributes on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeAttributes(boolean includeAttributes) {
this.includeAttributes = includeAttributes;
if (includeAttributes) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include the permission key on this listing operation.
*/
public boolean includePermissionKey() {
return includePermissionKey;
}
/**
* @param includePermissionKey whether to include the permission key on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludePermissionKey(boolean includePermissionKey) {
this.includePermissionKey = includePermissionKey;
if (includePermissionKey) {
this.includeExtendedInfo = true;
}
return this;
}
} | class ShareListFilesAndDirectoriesOptions {
private final ClientLogger logger = new ClientLogger(ShareListFilesAndDirectoriesOptions.class);
private String prefix;
private Integer maxResultsPerPage;
private boolean includeTimestamps;
private boolean includeETag;
private boolean includeAttributes;
private boolean includePermissionKey;
private Boolean includeExtendedInfo;
/**
* @return prefix for this listing operation.
*/
public String getPrefix() {
return prefix;
}
/**
* Sets the prefix for a listing operation.
*
* @param prefix the prefix.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
/**
* @return max results per page for this listing operation.
*/
public Integer getMaxResultsPerPage() {
return maxResultsPerPage;
}
/**
* Sets the max results per page for a listing operation.
*
* @param maxResultsPerPage the max results per page.
* @return updated options.
*/
public ShareListFilesAndDirectoriesOptions setMaxResultsPerPage(Integer maxResultsPerPage) {
this.maxResultsPerPage = maxResultsPerPage;
return this;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false while any of these options are true will be unsuccessful.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @return whether to include extended info on this listing operation.
*/
public Boolean includeExtendedInfo() {
return includeExtendedInfo;
}
/**
* Note that setting timestamps, etag, attributes, or permission key will also set this option as true. Attempting
* to set it back to false will be unsuccessful.
*
* Sets the prefix for a listing operation.
*
* Including extended info in a listing operation can result in a more expensive operation, but will present
* more accurate information on the listing item.
*
* @param includeExtendedInfo whether to include extended info.
* @return updated options.
* @throws IllegalStateException Throws when attempting to set null when other parameters require it to be true.
*/
public ShareListFilesAndDirectoriesOptions setIncludeExtendedInfo(Boolean includeExtendedInfo) {
if (includeTimestamps || includeETag || includeAttributes || includePermissionKey) {
throw logger.logExceptionAsError(
new IllegalStateException("includeExtendedInfo must be true in the current state."));
}
this.includeExtendedInfo = includeExtendedInfo;
return this;
}
/**
* @return whether to include timestamps on this listing operation.
*/
public boolean includeTimestamps() {
return includeTimestamps;
}
/**
* @param includeTimestamps whether to include timestamps on this listing operation.
* @return updated options
*/
/**
* @return whether to include the etag on this listing operation.
*/
public boolean includeETag() {
return includeETag;
}
/**
* @param includeETag whether to include the etag on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeETag(boolean includeETag) {
this.includeETag = includeETag;
if (includeETag) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include file attributes on this listing operation.
*/
public boolean includeAttributes() {
return includeAttributes;
}
/**
* @param includeAttributes whether to include file attributes on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludeAttributes(boolean includeAttributes) {
this.includeAttributes = includeAttributes;
if (includeAttributes) {
this.includeExtendedInfo = true;
}
return this;
}
/**
* @return whether to include the permission key on this listing operation.
*/
public boolean includePermissionKey() {
return includePermissionKey;
}
/**
* @param includePermissionKey whether to include the permission key on this listing operation.
* @return updated options
*/
public ShareListFilesAndDirectoriesOptions setIncludePermissionKey(boolean includePermissionKey) {
this.includePermissionKey = includePermissionKey;
if (includePermissionKey) {
this.includeExtendedInfo = true;
}
return this;
}
} |
Key Vault docs don't actually mention AES. I'd just use "OCT" or "symmetric key". | Mono<Response<KeyVaultKey>> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions, Context context) {
Objects.requireNonNull(createOctKeyOptions, "The create key options cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createOctKeyOptions.getKeyType())
.setKeyOps(createOctKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createOctKeyOptions))
.setTags(createOctKeyOptions.getTags());
return service.createKey(vaultUrl, createOctKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating AES key - {}", createOctKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created AES key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create AES key - {}", createOctKeyOptions.getName(), error));
} | .doOnRequest(ignored -> logger.verbose("Creating AES key - {}", createOctKeyOptions.getName())) | new KeyRequestParameters().setKty(keyType);
return service.createKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating key - {} | class KeyAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1);
private final String vaultUrl;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
private final HttpPipeline pipeline;
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(vaultUrl,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
this.pipeline = pipeline;
apiVersion = version.getVersion();
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
HttpPipeline getHttpPipeline() {
return this.pipeline;
}
Duration getDefaultPollingInterval() {
return DEFAULT_POLLING_INTERVAL;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include:
* {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpResponseException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include:
* {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpResponseException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.verbose("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* include: {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions))
.setTags(createKeyOptions.getTags());
return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions))
.setPublicExponent(createRsaKeyOptions.getPublicExponent())
.setTags(createRsaKeyOptions.getTags());
return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurveName())
.setKeyOps(createEcKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions))
.setTags(createEcKeyOptions.getTags());
return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Creates and stores a new AES key in Key Vault. If the named key already exists, Azure Key Vault creates a new
* version of the key. This operation requires the keys/create permission.
*
* <p>The {@link CreateOctKeyOptions} parameter is required. The {@link CreateOctKeyOptions
* and {@link CreateOctKeyOptions
* {@link CreateOctKeyOptions
*
* <p>The {@link CreateOctKeyOptions
* Possible values include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new AES key. The key activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created ec key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyAsyncClient.createOctKey
*
* @param createOctKeyOptions The key options object containing information about the ec key being created.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws NullPointerException If {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException If {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createOctKey(CreateOctKeyOptions createOctKeyOptions) {
try {
return createOctKeyWithResponse(createOctKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates and stores a new AES key in Key Vault. If the named key already exists, Azure Key Vault creates a new
* version of the key. This operation requires the keys/create permission.
*
* <p>The {@link CreateOctKeyOptions} parameter is required. The {@link CreateOctKeyOptions
* and {@link CreateOctKeyOptions
* {@link CreateOctKeyOptions
*
* <p>The {@link CreateOctKeyOptions
* Possible values include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new AES key. The key activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created ec key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyAsyncClient.createOctKeyWithResponse
*
* @param createOctKeyOptions The key options object containing information about the ec key being created.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey created key}.
*
* @throws NullPointerException If {@code createOctKeyOptions} is {@code null}.
* @throws ResourceModifiedException If {@code createOctKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions) {
try {
return withContext(context -> createOctKeyWithResponse(createOctKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions, Context context) {
Objects.requireNonNull(createOctKeyOptions, "The create key options cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createOctKeyOptions.getKeyType())
.setKeyOps(createOctKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createOctKeyOptions))
.setTags(createOctKeyOptions.getTags());
return service.createKey(vaultUrl, createOctKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating AES key - {}", createOctKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created AES key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create AES key - {}", createOctKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpResponseException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Importing key - {}", name))
.doOnSuccess(response -> logger.verbose("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions))
.setTags(importKeyOptions.getTags());
return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* The content of the key is null if both {@code name} and {@code version} are null or empty.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or
* an empty/null {@code name} and a non null/empty {@code version} is provided.
* @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version}
* are null or empty.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or
* an empty/null {@code name} and a non null/empty {@code version} is provided.
* @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Retrieving key - {}", name))
.doOnSuccess(response -> logger.verbose("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null
* if {@code name} is null or empty.
* @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault.
* @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpResponseException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpResponseException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) {
Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setTags(keyProperties.getTags())
.setKeyAttributes(new KeyRequestAttributes(keyProperties));
if (keyOperations.length > 0) {
parameters.setKeyOps(Arrays.asList(keyOperations));
}
return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Updating key - {}", keyProperties.getName()))
.doOnSuccess(response -> logger.verbose("Updated key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error));
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) {
return beginDeleteKey(name, getDefaultPollingInterval());
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @param pollingInterval The interval at which the operation status will be polled for.
* @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) {
return new PollerFlux<>(pollingInterval,
activationOperation(name),
createPollOperation(name),
(context, firstResponse) -> Mono.empty(),
(context) -> Mono.empty());
}
private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) {
return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context))
.flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue()));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(deletedKeyResponse -> {
if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()));
}
Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) {
return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Deleting key - {}", name))
.doOnSuccess(response -> logger.verbose("Deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to delete key - {}", name, error));
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedKey> getDeletedKey(String name) {
try {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) {
try {
return withContext(context -> getDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) {
context = context == null ? Context.NONE : context;
return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Retrieving deleted key - {}", name))
.doOnSuccess(response -> logger.verbose("Retrieved deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey
*
* @param name The name of the deleted key.
* @return An empty {@link Mono}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedKey(String name) {
try {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) {
try {
return withContext(context -> purgeDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) {
context = context == null ? Context.NONE : context;
return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Purging deleted key - {}", name))
.doOnSuccess(response -> logger.verbose("Purged deleted key - {}", name))
.doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error));
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) {
return beginRecoverDeletedKey(name, getDefaultPollingInterval());
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @param pollingInterval The interval at which the operation status will be polled for.
* @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) {
return new PollerFlux<>(pollingInterval,
recoverActivationOperation(name),
createRecoverPollOperation(name),
(context, firstResponse) -> Mono.empty(),
context -> Mono.empty());
}
private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) {
return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context))
.flatMap(keyResponse -> Mono.just(keyResponse.getValue()));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(keyResponse -> {
if (keyResponse.getStatusCode() == 404) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
keyResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue()));
}
Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) {
return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Recovering deleted key - {}", name))
.doOnSuccess(response -> logger.verbose("Recovered deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error));
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the backed up key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<byte[]> backupKey(String name) {
try {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse
*
* @param name The name of the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<byte[]>> backupKeyWithResponse(String name) {
try {
return withContext(context -> backupKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) {
context = context == null ? Context.NONE : context;
return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Backing up key - {}", name))
.doOnSuccess(response -> logger.verbose("Backed up key - {}", name))
.doOnError(error -> logger.warning("Failed to backup key - {}", name, error))
.flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(),
base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue())));
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) {
try {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) {
try {
return withContext(context -> restoreKeyBackupWithResponse(backup, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) {
context = context == null ? Context.NONE : context;
KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup);
return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Attempting to restore key"))
.doOnSuccess(response -> logger.verbose("Restored Key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to restore key - {}", error));
}
/**
* List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain
* the public part of a stored key. The List operation is applicable to all key types and the individual key
* response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing
* {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys}
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeysFirstPage(context)),
continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) {
return new PagedFlux<>(
() -> listKeysFirstPage(context),
continuationToken -> listKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing next keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.verbose("Listed next keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) {
try {
return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing keys"))
.doOnSuccess(response -> logger.verbose("Listed keys"))
.doOnError(error -> logger.warning("Failed to list keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures
* that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled
* for soft-delete. This operation requires the {@code keys/list} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id
* of each deleted key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys}
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DeletedKey> listDeletedKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listDeletedKeysFirstPage(context)),
continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DeletedKey> listDeletedKeys(Context context) {
return new PagedFlux<>(
() -> listDeletedKeysFirstPage(context),
continuationToken -> listDeletedKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* list operations.
* @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) {
try {
return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing next deleted keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.verbose("Listed next deleted keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) {
try {
return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing deleted keys"))
.doOnSuccess(response -> logger.verbose("Listed deleted keys"))
.doOnError(error -> logger.warning("Failed to list deleted keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties}
* as only the key identifier, attributes and tags are provided in the response. The key material values are
* not provided in the response. This operation requires the {@code keys/list} permission.
*
* <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link
* Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions}
*
* @param name The name of the key.
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault.
* Flux is empty if key with {@code name} does not exist in key vault.
* @throws ResourceNotFoundException when a given key {@code name} is null or an empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeyVersionsFirstPage(name, context)),
continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) {
return new PagedFlux<>(
() -> listKeyVersionsFirstPage(name, context),
continuationToken -> listKeyVersionsNextPage(continuationToken, context));
}
private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) {
try {
return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing key versions - {}", name))
.doOnSuccess(response -> logger.verbose("Listed key versions - {}", name))
.doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing next key versions page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.verbose("Listed next key versions page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} | class KeyAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1);
private final String vaultUrl;
private final KeyService service;
private final ClientLogger logger = new ClientLogger(KeyAsyncClient.class);
private final HttpPipeline pipeline;
/**
* Creates a KeyAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link KeyServiceVersion} of the service to be used when making requests.
*/
KeyAsyncClient(URL vaultUrl, HttpPipeline pipeline, KeyServiceVersion version) {
Objects.requireNonNull(vaultUrl,
KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(KeyService.class, pipeline);
this.pipeline = pipeline;
apiVersion = version.getVersion();
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Gets the {@link HttpPipeline} powering this client.
*
* @return The pipeline.
*/
HttpPipeline getHttpPipeline() {
return this.pipeline;
}
Duration getDefaultPollingInterval() {
return DEFAULT_POLLING_INTERVAL;
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include:
* {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param name The name of the key being created.
* @param keyType The type of key to create. For valid values, see {@link KeyType KeyType}.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpResponseException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(String name, KeyType keyType) {
try {
return withContext(context -> createKeyWithResponse(name, keyType, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link KeyType keyType} indicates the type of key to create. Possible values include:
* {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key. Subscribes to the call asynchronously and prints out the newly created key details when
* a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKeyWithResponse
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws ResourceModifiedException if {@code name} or {@code keyType} is null.
* @throws HttpResponseException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions) {
try {
return withContext(context -> createKeyWithResponse(createKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(String name, KeyType keyType, Context context) {
KeyRequestParameters parameters = ", name))
.doOnSuccess(response -> logger.verbose("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", name, error));
}
/**
* Creates a new key and stores it in the key vault. The create key operation can be used to create any key type in
* key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the
* {@code keys/create} permission.
*
* <p>The {@link CreateKeyOptions} is required. The {@link CreateKeyOptions
* CreateKeyOptions
* field is set to true by Azure Key Vault, if not specified.</p>
*
* <p>The {@link CreateKeyOptions
* include: {@link KeyType
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new Rsa key which activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createKey
*
* @param createKeyOptions The key configuration object containing information about the key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code keyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code keyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createKey(CreateKeyOptions createKeyOptions) {
try {
return createKeyWithResponse(createKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createKeyWithResponse(CreateKeyOptions createKeyOptions, Context context) {
Objects.requireNonNull(createKeyOptions, "The key create options parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createKeyOptions.getKeyType())
.setKeyOps(createKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createKeyOptions))
.setTags(createKeyOptions.getTags());
return service.createKey(vaultUrl, createKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating key - {}", createKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create key - {}", createKeyOptions.getName(), error));
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new RSA key with size 2048 which activates in one day and expires in one year. Subscribes to the
* call asynchronously and prints out the newly created key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKey
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createRsaKey(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return createRsaKeyWithResponse(createRsaKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Rsa key and stores it in the key vault. The create Rsa key operation can be used to create any Rsa
* key type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It
* requires the {@code keys/create} permission.
*
* <p>The {@link CreateRsaKeyOptions} is required. The {@link CreateRsaKeyOptions
* optionally specified. The {@link CreateRsaKeyOptions
* {@link CreateRsaKeyOptions
* CreateRsaKeyOptions
*
* <p>The {@link CreateRsaKeyOptions
* include: {@link KeyType
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createRsaKeyWithResponse
*
* @param createRsaKeyOptions The key configuration object containing information about the rsa key being
* created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code rsaKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code rsaKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions) {
try {
return withContext(context -> createRsaKeyWithResponse(createRsaKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createRsaKeyWithResponse(CreateRsaKeyOptions createRsaKeyOptions, Context context) {
Objects.requireNonNull(createRsaKeyOptions, "The Rsa key options parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createRsaKeyOptions.getKeyType())
.setKeySize(createRsaKeyOptions.getKeySize())
.setKeyOps(createRsaKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createRsaKeyOptions))
.setPublicExponent(createRsaKeyOptions.getPublicExponent())
.setTags(createRsaKeyOptions.getTags());
return service.createKey(vaultUrl, createRsaKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating Rsa key - {}", createRsaKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created Rsa key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Rsa key - {}", createRsaKeyOptions.getName(), error));
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* if not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKey
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createEcKey(CreateEcKeyOptions createEcKeyOptions) {
try {
return createEcKeyWithResponse(createEcKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a new Ec key and stores it in the key vault. The create Ec key operation can be used to create any Ec key
* type in key vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires
* the {@code keys/create} permission.
*
* <p>The {@link CreateEcKeyOptions} parameter is required. The {@link CreateEcKeyOptions
* optionally specified. If not specified, default value of {@link KeyCurveName
* Vault. The {@link CreateEcKeyOptions
* values are optional. The {@link CreateEcKeyOptions
* not specified.</p>
*
* <p>The {@link CreateEcKeyOptions
* {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new EC key with P-384 web key curve. The key activates in one day and expires in one year.
* Subscribes to the call asynchronously and prints out the newly created ec key details when a response has been
* received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.createEcKeyWithResponse
*
* @param createEcKeyOptions The key options object containing information about the ec key being created.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* created key}.
* @throws NullPointerException if {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException if {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions) {
try {
return withContext(context -> createEcKeyWithResponse(createEcKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createEcKeyWithResponse(CreateEcKeyOptions createEcKeyOptions, Context context) {
Objects.requireNonNull(createEcKeyOptions, "The Ec key options cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createEcKeyOptions.getKeyType())
.setCurve(createEcKeyOptions.getCurveName())
.setKeyOps(createEcKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createEcKeyOptions))
.setTags(createEcKeyOptions.getTags());
return service.createKey(vaultUrl, createEcKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating Ec key - {}", createEcKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created Ec key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to create Ec key - {}", createEcKeyOptions.getName(), error));
}
/**
* Creates and stores a new symmetric key in Key Vault. If the named key already exists, Azure Key Vault creates a
* new version of the key. This operation requires the keys/create permission.
*
* <p>The {@link CreateOctKeyOptions} parameter is required. The {@link CreateOctKeyOptions
* and {@link CreateOctKeyOptions
* {@link CreateOctKeyOptions
*
* <p>The {@link CreateOctKeyOptions
* Possible values include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new symmetric key. The key activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the details of the newly created key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyAsyncClient.createOctKey
*
* @param createOctKeyOptions The key options object containing information about the ec key being created.
*
* @return A {@link Mono} containing the {@link KeyVaultKey created key}.
*
* @throws NullPointerException If {@code ecKeyCreateOptions} is {@code null}.
* @throws ResourceModifiedException If {@code ecKeyCreateOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> createOctKey(CreateOctKeyOptions createOctKeyOptions) {
try {
return createOctKeyWithResponse(createOctKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates and stores a new symmetric key in Key Vault. If the named key already exists, Azure Key Vault creates
* a new version of the key. This operation requires the keys/create permission.
*
* <p>The {@link CreateOctKeyOptions} parameter is required. The {@link CreateOctKeyOptions
* and {@link CreateOctKeyOptions
* {@link CreateOctKeyOptions
*
* <p>The {@link CreateOctKeyOptions
* Possible values include: {@link KeyType
*
* <p><strong>Code Samples</strong></p>
* <p>Creates a new symmetric key. The key activates in one day and expires in one year. Subscribes to the call
* asynchronously and prints out the details of the newly created key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyAsyncClient.createOctKeyWithResponse
*
* @param createOctKeyOptions The key options object containing information about the ec key being created.
*
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey created key}.
*
* @throws NullPointerException If {@code createOctKeyOptions} is {@code null}.
* @throws ResourceModifiedException If {@code createOctKeyOptions} is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions) {
try {
return withContext(context -> createOctKeyWithResponse(createOctKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> createOctKeyWithResponse(CreateOctKeyOptions createOctKeyOptions, Context context) {
Objects.requireNonNull(createOctKeyOptions, "The create key options cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setKty(createOctKeyOptions.getKeyType())
.setKeyOps(createOctKeyOptions.getKeyOperations())
.setKeyAttributes(new KeyRequestAttributes(createOctKeyOptions))
.setTags(createOctKeyOptions.getTags());
return service.createKey(vaultUrl, createOctKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Creating symmetric key - {}", createOctKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Created symmetric key - {}", response.getValue().getName()))
.doOnError(error ->
logger.warning("Failed to create symmetric key - {}", createOctKeyOptions.getName(), error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey
*
* @param name The name for the imported key.
* @param keyMaterial The Json web key being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws HttpResponseException if {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(String name, JsonWebKey keyMaterial) {
try {
return withContext(context -> importKeyWithResponse(name, keyMaterial, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(String name, JsonWebKey keyMaterial, Context context) {
KeyImportRequestParameters parameters = new KeyImportRequestParameters().setKey(keyMaterial);
return service.importKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Importing key - {}", name))
.doOnSuccess(response -> logger.verbose("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", name, error));
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* {@link ImportKeyOptions
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKey
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing the {@link KeyVaultKey imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> importKey(ImportKeyOptions importKeyOptions) {
try {
return importKeyWithResponse(importKeyOptions).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Imports an externally created key and stores it in key vault. The import key operation may be used to import any
* key type into the Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the
* key. This operation requires the {@code keys/import} permission.
*
* <p>The {@code keyImportOptions} is required and its fields {@link ImportKeyOptions
* ImportKeyOptions
* {@link ImportKeyOptions
* no values are set for the fields. The {@link ImportKeyOptions
* field is set to true and the {@link ImportKeyOptions
* are not specified.</p>
*
* <p><strong>Code Samples</strong></p>
* <p>Imports a new key into key vault. Subscribes to the call asynchronously and prints out the newly imported key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.keyasyncclient.importKeyWithResponse
*
* @param importKeyOptions The key import configuration object containing information about the json web key
* being imported.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* imported key}.
* @throws NullPointerException if {@code keyImportOptions} is {@code null}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions) {
try {
return withContext(context -> importKeyWithResponse(importKeyOptions, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> importKeyWithResponse(ImportKeyOptions importKeyOptions, Context context) {
Objects.requireNonNull(importKeyOptions, "The key import configuration parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyImportRequestParameters parameters = new KeyImportRequestParameters()
.setKey(importKeyOptions.getKey())
.setHsm(importKeyOptions.isHardwareProtected())
.setKeyAttributes(new KeyRequestAttributes(importKeyOptions))
.setTags(importKeyOptions.getTags());
return service.importKey(vaultUrl, importKeyOptions.getName(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Importing key - {}", importKeyOptions.getName()))
.doOnSuccess(response -> logger.verbose("Imported key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to import key - {}", importKeyOptions.getName(), error));
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}.
* The content of the key is null if both {@code name} and {@code version} are null or empty.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or
* an empty/null {@code name} and a non null/empty {@code version} is provided.
* @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name, String version) {
try {
return getKeyWithResponse(name, version).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of the specified key and key version. The get key operation is applicable to all key types
* and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKeyWithResponse
*
* @param name The name of the key, cannot be null
* @param version The version of the key to retrieve. If this is an empty String or null, this call is
* equivalent to calling {@link KeyAsyncClient
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* {@link KeyVaultKey key}. The content of the key is null if both {@code name} and {@code version}
* are null or empty.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault or
* an empty/null {@code name} and a non null/empty {@code version} is provided.
* @throws HttpResponseException if a valid {@code name} and a non null/empty {@code version} is specified.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version) {
try {
return withContext(context -> getKeyWithResponse(name, version == null ? "" : version, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> getKeyWithResponse(String name, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getKey(vaultUrl, name, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Retrieving key - {}", name))
.doOnSuccess(response -> logger.verbose("Retrieved key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Get the public part of the latest version of the specified key from the key vault. The get key operation is
* applicable to all key types and it requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key in the key vault. Subscribes to the call asynchronously and prints out the
* returned key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the requested {@link KeyVaultKey key}. The content of the key is null
* if {@code name} is null or empty.
* @throws ResourceNotFoundException when a key with non null/empty {@code name} doesn't exist in the key vault.
* @throws HttpResponseException if a non null/empty and an invalid {@code name} is specified.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> getKey(String name) {
try {
return getKeyWithResponse(name, "").flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyPropertiesWithResponse
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpResponseException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return withContext(context -> updateKeyPropertiesWithResponse(keyProperties, context, keyOperations));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the attributes and key operations associated with the specified key, but not the cryptographic key
* material of the specified key in the key vault. The update operation changes specified attributes of an existing
* stored key and attributes that are not specified in the request are left unchanged. The cryptographic key
* material of a key itself cannot be changed. This operation requires the {@code keys/set} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the key, changes its notBefore time and then updates it in the Azure Key Vault.
* Subscribes to the call asynchronously and prints out the returned key details when a response has been received.
* </p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.updateKeyProperties
*
* @param keyProperties The {@link KeyProperties key properties} object with updated properties.
* @param keyOperations The updated key operations to associate with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey updated key}.
* @throws NullPointerException if {@code key} is {@code null}.
* @throws ResourceNotFoundException when a key with {@link KeyProperties
* version} doesn't exist in the key vault.
* @throws HttpResponseException if {@link KeyProperties
* string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> updateKeyProperties(KeyProperties keyProperties, KeyOperation... keyOperations) {
try {
return updateKeyPropertiesWithResponse(keyProperties, keyOperations).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) {
Objects.requireNonNull(keyProperties, "The key properties input parameter cannot be null.");
context = context == null ? Context.NONE : context;
KeyRequestParameters parameters = new KeyRequestParameters()
.setTags(keyProperties.getTags())
.setKeyAttributes(new KeyRequestAttributes(keyProperties));
if (keyOperations.length > 0) {
parameters.setKeyOps(Arrays.asList(keyOperations));
}
return service.updateKey(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Updating key - {}", keyProperties.getName()))
.doOnSuccess(response -> logger.verbose("Updated key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to update key - {}", keyProperties.getName(), error));
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<DeletedKey, Void> beginDeleteKey(String name) {
return beginDeleteKey(name, getDefaultPollingInterval());
}
/**
* Deletes a key of any type from the key vault. If soft-delete is enabled on the key vault then the key is placed
* in the deleted state and requires to be purged for permanent deletion else the key is permanently deleted. The
* delete operation applies to any key stored in Azure Key Vault but it cannot be applied to an individual version
* of a key. This operation removes the cryptographic material associated with the key, which means the key is not
* usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the
* {@code keys/delete} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the key in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted key
* details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.deleteKey
*
* @param name The name of the key to be deleted.
* @param pollingInterval The interval at which the operation status will be polled for.
* @return A {@link PollerFlux} to poll on the {@link DeletedKey deleted key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<DeletedKey, Void> beginDeleteKey(String name, Duration pollingInterval) {
return new PollerFlux<>(pollingInterval,
activationOperation(name),
createPollOperation(name),
(context, firstResponse) -> Mono.empty(),
(context) -> Mono.empty());
}
private Function<PollingContext<DeletedKey>, Mono<DeletedKey>> activationOperation(String name) {
return (pollingContext) -> withContext(context -> deleteKeyWithResponse(name, context))
.flatMap(deletedKeyResponse -> Mono.just(deletedKeyResponse.getValue()));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollingContext<DeletedKey>, Mono<PollResponse<DeletedKey>>> createPollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getDeletedKeyPoller(vaultUrl, keyName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(deletedKeyResponse -> {
if (deletedKeyResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedKeyResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()));
}
Mono<Response<DeletedKey>> deleteKeyWithResponse(String name, Context context) {
return service.deleteKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Deleting key - {}", name))
.doOnSuccess(response -> logger.verbose("Deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to delete key - {}", name, error));
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKey
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing the {@link DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedKey> getDeletedKey(String name) {
try {
return getDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the public part of a deleted key. The Get Deleted Key operation is applicable for soft-delete enabled
* vaults. This operation requires the {@code keys/get} permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the deleted key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.getDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* DeletedKey deleted key}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name) {
try {
return withContext(context -> getDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedKey>> getDeletedKeyWithResponse(String name, Context context) {
context = context == null ? Context.NONE : context;
return service.getDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Retrieving deleted key - {}", name))
.doOnSuccess(response -> logger.verbose("Retrieved deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to get key - {}", name, error));
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKey
*
* @param name The name of the deleted key.
* @return An empty {@link Mono}.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedKey(String name) {
try {
return purgeDeletedKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified key without the possibility of recovery. The Purge Deleted Key operation is
* applicable for soft-delete enabled vaults. This operation requires the {@code keys/purge} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the status code from the server response when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.purgeDeletedKeyWithResponse
*
* @param name The name of the deleted key.
* @return A {@link Mono} containing a Response containing status code and HTTP headers.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> purgeDeletedKeyWithResponse(String name) {
try {
return withContext(context -> purgeDeletedKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> purgeDeletedKeyWithResponse(String name, Context context) {
context = context == null ? Context.NONE : context;
return service.purgeDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Purging deleted key - {}", name))
.doOnSuccess(response -> logger.verbose("Purged deleted key - {}", name))
.doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error));
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name) {
return beginRecoverDeletedKey(name, getDefaultPollingInterval());
}
/**
* Recovers the deleted key in the key vault to its latest version and can only be performed on a soft-delete
* enabled vault. An attempt to recover an non-deleted key will return an error. Consider this the inverse of the
* delete operation on soft-delete enabled vaults. This operation requires the {@code keys/recover} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Recovers the deleted key from the key vault enabled for soft-delete. Subscribes to the call asynchronously and
* prints out the recovered key details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.recoverDeletedKey
*
* @param name The name of the deleted key to be recovered.
* @param pollingInterval The interval at which the operation status will be polled for.
* @return A {@link PollerFlux} to poll on the {@link KeyVaultKey recovered key} status.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<KeyVaultKey, Void> beginRecoverDeletedKey(String name, Duration pollingInterval) {
return new PollerFlux<>(pollingInterval,
recoverActivationOperation(name),
createRecoverPollOperation(name),
(context, firstResponse) -> Mono.empty(),
context -> Mono.empty());
}
private Function<PollingContext<KeyVaultKey>, Mono<KeyVaultKey>> recoverActivationOperation(String name) {
return (pollingContext) -> withContext(context -> recoverDeletedKeyWithResponse(name, context))
.flatMap(keyResponse -> Mono.just(keyResponse.getValue()));
}
/*
Polling operation to poll on create delete key operation status.
*/
private Function<PollingContext<KeyVaultKey>, Mono<PollResponse<KeyVaultKey>>> createRecoverPollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getKeyPoller(vaultUrl, keyName, "", apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(keyResponse -> {
if (keyResponse.getStatusCode() == 404) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
keyResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue()));
}
Mono<Response<KeyVaultKey>> recoverDeletedKeyWithResponse(String name, Context context) {
return service.recoverDeletedKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Recovering deleted key - {}", name))
.doOnSuccess(response -> logger.verbose("Recovered deleted key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error));
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKey
*
* @param name The name of the key.
* @return A {@link Mono} containing the backed up key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<byte[]> backupKey(String name) {
try {
return backupKeyWithResponse(name).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Requests a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from
* Azure Key Vault in a protected form. Note that this operation does not return key material in a form that can be
* used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM
* or to Azure Key Vault itself. The intent of this operation is to allow a client to generate a key in one Azure
* Key Vault instance, backup the key, and then restore it into another Azure Key Vault instance. The backup
* operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a
* key cannot be backed up. Backup / Restore can be performed within geographical boundaries only; meaning that a
* backup from one geographical area cannot be restored to another geographical area. For example, a backup from the
* US geographical area cannot be restored in an EU geographical area. This operation requires the {@code
* key/backup} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Backs up the key from the key vault. Subscribes to the call asynchronously and prints out the length of the
* key's backup byte array returned in the response.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.backupKeyWithResponse
*
* @param name The name of the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* key blob.
* @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault.
* @throws HttpResponseException when a key with {@code name} is empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<byte[]>> backupKeyWithResponse(String name) {
try {
return withContext(context -> backupKeyWithResponse(name, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<byte[]>> backupKeyWithResponse(String name, Context context) {
context = context == null ? Context.NONE : context;
return service.backupKey(vaultUrl, name, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Backing up key - {}", name))
.doOnSuccess(response -> logger.verbose("Backed up key - {}", name))
.doOnError(error -> logger.warning("Failed to backup key - {}", name, error))
.flatMap(base64URLResponse -> Mono.just(new SimpleResponse<byte[]>(base64URLResponse.getRequest(),
base64URLResponse.getStatusCode(), base64URLResponse.getHeaders(), base64URLResponse.getValue().getValue())));
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackup
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing the {@link KeyVaultKey restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultKey> restoreKeyBackup(byte[] backup) {
try {
return restoreKeyBackupWithResponse(backup).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Restores a backed up key to a vault. Imports a previously backed up key into Azure Key Vault, restoring the key,
* its key identifier, attributes and access control policies. The restore operation may be used to import a
* previously backed up key. The individual versions of a key cannot be restored. The key is restored in its
* entirety with the same key name as it had when it was backed up. If the key name is not available in the target
* Key Vault, the restore operation will be rejected. While the key name is retained during restore, the final key
* identifier will change if the key is restored to a different vault. Restore will restore all versions and
* preserve version identifiers. The restore operation is subject to security constraints: The target Key Vault must
* be owned by the same Microsoft Azure Subscription as the source Key Vault The user must have restore permission
* in the target Key Vault. This operation requires the {@code keys/restore} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Restores the key in the key vault from its backup. Subscribes to the call asynchronously and prints out the
* restored key details when a response has been received.</p>
*
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.restoreKeyBackupWithResponse
*
* @param backup The backup blob associated with the key.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
* restored key}.
* @throws ResourceModifiedException when {@code backup} blob is malformed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup) {
try {
return withContext(context -> restoreKeyBackupWithResponse(backup, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultKey>> restoreKeyBackupWithResponse(byte[] backup, Context context) {
context = context == null ? Context.NONE : context;
KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().setKeyBackup(backup);
return service.restoreKey(vaultUrl, apiVersion, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Attempting to restore key"))
.doOnSuccess(response -> logger.verbose("Restored Key - {}", response.getValue().getName()))
.doOnError(error -> logger.warning("Failed to restore key - {}", error));
}
/**
* List keys in the key vault. Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain
* the public part of a stored key. The List operation is applicable to all key types and the individual key
* response in the flux is represented by {@link KeyProperties} as only the key identifier, attributes and tags are
* provided in the response. The key material and individual key versions are not listed in the response. This
* operation requires the {@code keys/list} permission.
*
* <p>It is possible to get full keys with key material from this information. Convert the {@link Flux} containing
* {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeys}
*
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the keys in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeysFirstPage(context)),
continuationToken -> withContext(context -> listKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeys(Context context) {
return new PagedFlux<>(
() -> listKeysFirstPage(context),
continuationToken -> listKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeysNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing next keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.verbose("Listed next keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<KeyProperties>> listKeysFirstPage(Context context) {
try {
return service.getKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing keys"))
.doOnSuccess(response -> logger.verbose("Listed keys"))
.doOnError(error -> logger.warning("Failed to list keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Lists {@link DeletedKey deleted keys} of the key vault. The deleted keys are retrieved as JSON Web Key structures
* that contain the public part of a deleted key. The Get Deleted Keys operation is applicable for vaults enabled
* for soft-delete. This operation requires the {@code keys/list} permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Lists the deleted keys in the key vault. Subscribes to the call asynchronously and prints out the recovery id
* of each deleted key when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listDeletedKeys}
*
* @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DeletedKey> listDeletedKeys() {
try {
return new PagedFlux<>(
() -> withContext(context -> listDeletedKeysFirstPage(context)),
continuationToken -> withContext(context -> listDeletedKeysNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DeletedKey> listDeletedKeys(Context context) {
return new PagedFlux<>(
() -> listDeletedKeysFirstPage(context),
continuationToken -> listDeletedKeysNextPage(continuationToken, context));
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* list operations.
* @return A {@link Mono} of {@link PagedResponse<DeletedKey>} from the next page of results.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysNextPage(String continuationToken, Context context) {
try {
return service.getDeletedKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing next deleted keys page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.verbose("Listed next deleted keys page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Calls the service and retrieve first page result. It makes one call and retrieve {@code
* DEFAULT_MAX_PAGE_RESULTS} values.
*/
private Mono<PagedResponse<DeletedKey>> listDeletedKeysFirstPage(Context context) {
try {
return service.getDeletedKeys(vaultUrl, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing deleted keys"))
.doOnSuccess(response -> logger.verbose("Listed deleted keys"))
.doOnError(error -> logger.warning("Failed to list deleted keys", error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* List all versions of the specified key. The individual key response in the flux is represented by {@link KeyProperties}
* as only the key identifier, attributes and tags are provided in the response. The key material values are
* not provided in the response. This operation requires the {@code keys/list} permission.
*
* <p>It is possible to get the keys with key material of all the versions from this information. Convert the {@link
* Flux} containing {@link KeyProperties key properties} to {@link Flux} containing {@link KeyVaultKey key} using
* {@link KeyAsyncClient
*
* {@codesnippet com.azure.security.keyvault.keys.async.keyclient.listKeyVersions}
*
* @param name The name of the key.
* @return A {@link PagedFlux} containing {@link KeyProperties key} of all the versions of the specified key in the vault.
* Flux is empty if key with {@code name} does not exist in key vault.
* @throws ResourceNotFoundException when a given key {@code name} is null or an empty string.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name) {
try {
return new PagedFlux<>(
() -> withContext(context -> listKeyVersionsFirstPage(name, context)),
continuationToken -> withContext(context -> listKeyVersionsNextPage(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<KeyProperties> listPropertiesOfKeyVersions(String name, Context context) {
return new PagedFlux<>(
() -> listKeyVersionsFirstPage(name, context),
continuationToken -> listKeyVersionsNextPage(continuationToken, context));
}
private Mono<PagedResponse<KeyProperties>> listKeyVersionsFirstPage(String name, Context context) {
try {
return service.getKeyVersions(vaultUrl, name, DEFAULT_MAX_PAGE_RESULTS, apiVersion, ACCEPT_LANGUAGE,
CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing key versions - {}", name))
.doOnSuccess(response -> logger.verbose("Listed key versions - {}", name))
.doOnError(error -> logger.warning(String.format("Failed to list key versions - %s", name), error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/*
* Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to
* {@link KeyAsyncClient
*
* @param continuationToken The {@link PagedResponse
* listKeys operations.
* @return A {@link Mono} of {@link PagedResponse<KeyProperties>} from the next page of results.
*/
private Mono<PagedResponse<KeyProperties>> listKeyVersionsNextPage(String continuationToken, Context context) {
try {
return service.getKeys(vaultUrl, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.verbose("Listing next key versions page - Page {} ", continuationToken))
.doOnSuccess(response -> logger.verbose("Listed next key versions page - Page {} ", continuationToken))
.doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken,
error));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
} |
not sure what this comment is for.. there is no training in recognize content | public static void main(final String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/Form_1.jpg");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContent(toFluxByteBuffer(targetStream), sourceFile.length());
Mono<List<FormPage>> contentPageResultsMono =
recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED.equals(pollResponse.getStatus())) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(
new RuntimeException(
"Polling completed unsuccessfully with status:" + pollResponse.getStatus()));
}
});
contentPageResultsMono.subscribe(contentPageResults -> {
for (int i = 0; i < contentPageResults.size(); i++) {
final FormPage formPage = contentPageResults.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
formTableCell.getBoundingBox().toString());
});
System.out.println();
}
formPage.getLines().forEach(formLine -> {
if (formLine.getAppearance() != null) {
System.out.printf(
"Line %s consists of %d words and has a text style %s with a confidence score of %.2f.%n",
formLine.getText(), formLine.getWords().size(),
formLine.getAppearance().getStyleName(),
formLine.getAppearance().getStyleConfidence());
}
});
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | public static void main(final String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContent(toFluxByteBuffer(targetStream), sourceFile.length());
Mono<List<FormPage>> contentPageResultsMono =
recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED.equals(pollResponse.getStatus())) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(
new RuntimeException(
"Polling completed unsuccessfully with status:" + pollResponse.getStatus()));
}
});
contentPageResultsMono.subscribe(contentPageResults -> {
for (int i = 0; i < contentPageResults.size(); i++) {
final FormPage formPage = contentPageResults.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
formTableCell.getBoundingBox().toString());
});
System.out.println();
}
for (FormSelectionMark selectionMark : formPage.getSelectionMarks()) {
System.out.printf(
"Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence());
}
formPage.getLines().forEach(formLine -> {
if (formLine.getAppearance() != null) {
System.out.printf(
"Line %s consists of %d words and has a text style %s with a confidence score of %.2f.%n",
formLine.getText(), formLine.getWords().size(),
formLine.getAppearance().getStyleName(),
formLine.getAppearance().getStyleConfidence());
}
});
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeContentAsync {
/**
* 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.
*/
} | class RecognizeContentAsync {
/**
* 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.
*/
} | |
in .NET we are showing, tables, lines, and selection marks. In case you will like to expand the input, see https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/samples/Sample1_RecognizeFormContent.md | public static void main(final String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/Form_1.jpg");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContent(toFluxByteBuffer(targetStream), sourceFile.length());
Mono<List<FormPage>> contentPageResultsMono =
recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED.equals(pollResponse.getStatus())) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(
new RuntimeException(
"Polling completed unsuccessfully with status:" + pollResponse.getStatus()));
}
});
contentPageResultsMono.subscribe(contentPageResults -> {
for (int i = 0; i < contentPageResults.size(); i++) {
final FormPage formPage = contentPageResults.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
formTableCell.getBoundingBox().toString());
});
System.out.println();
}
formPage.getLines().forEach(formLine -> {
if (formLine.getAppearance() != null) {
System.out.printf(
"Line %s consists of %d words and has a text style %s with a confidence score of %.2f.%n",
formLine.getText(), formLine.getWords().size(),
formLine.getAppearance().getStyleName(),
formLine.getAppearance().getStyleConfidence());
}
});
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | final List<FormTable> tables = formPage.getTables(); | public static void main(final String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStream = new ByteArrayInputStream(fileContent);
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContent(toFluxByteBuffer(targetStream), sourceFile.length());
Mono<List<FormPage>> contentPageResultsMono =
recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (LongRunningOperationStatus.SUCCESSFULLY_COMPLETED.equals(pollResponse.getStatus())) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(
new RuntimeException(
"Polling completed unsuccessfully with status:" + pollResponse.getStatus()));
}
});
contentPageResultsMono.subscribe(contentPageResults -> {
for (int i = 0; i < contentPageResults.size(); i++) {
final FormPage formPage = contentPageResults.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
formTableCell.getBoundingBox().toString());
});
System.out.println();
}
for (FormSelectionMark selectionMark : formPage.getSelectionMarks()) {
System.out.printf(
"Page: %s, Selection mark is %s within bounding box %s has a confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence());
}
formPage.getLines().forEach(formLine -> {
if (formLine.getAppearance() != null) {
System.out.printf(
"Line %s consists of %d words and has a text style %s with a confidence score of %.2f.%n",
formLine.getText(), formLine.getWords().size(),
formLine.getAppearance().getStyleName(),
formLine.getAppearance().getStyleConfidence());
}
});
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeContentAsync {
/**
* 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.
*/
} | class RecognizeContentAsync {
/**
* 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.
*/
} |
what changed that now the samples don't need that `java` directory? or has this been wrong all the time? | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} |
if it was wrong, don't the samples run in the CI? have they always been failing and no one noticed? | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} |
Unfortunately, we currently don't have support on running samples in the CI. It is been failed all the time. | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} |
oh no. how sad :( is this global for all Java? | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} |
Yes. I talked to Alan about it. We will have a discussion about it. | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/" | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources/"
+ "sample-forms/forms/selectionMarkForm.pdf");
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
String modelId = "{modelId}";
PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller;
try (InputStream targetStream = new ByteArrayInputStream(fileContent)) {
recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream),
sourceFile.length(), new RecognizeCustomFormsOptions().setFieldElementsIncluded(true));
}
Mono<List<RecognizedForm>> recognizeFormResult =
recognizeFormPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
recognizeFormResult.subscribe(recognizedForms -> {
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm form = recognizedForms.get(i);
System.out.printf("----------- Recognized custom form info for page %d -----------%n", i);
System.out.printf("Form type: %s%n", form.getFormType());
System.out.printf("Form has form type confidence : %.2f%n", form.getFormTypeConfidence());
System.out.printf("Form was analyzed with model with ID: %s%n", form.getModelId());
form.getFields().forEach((label, formField) -> {
System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label,
formField.getLabelData().getText(),
formField.getConfidence());
});
final List<FormPage> pages = form.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormSelectionMark)
.map(formContent -> (FormSelectionMark) (formContent))
.forEach(selectionMark ->
System.out.printf("Page: %s, Selection mark is %s within bounding box %s has a "
+ "confidence score %.2f.%n",
selectionMark.getPageNumber(),
selectionMark.getState(),
selectionMark.getBoundingBox().toString(),
selectionMark.getConfidence()));
});
System.out.println();
}
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} | class RecognizeCustomFormsAsyncWithSelectionMarks {
/**
* 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.
*/
} |
How about default value AMQP? | public TransportType convert(String s) {
if (s == null) {
throw new ParameterException(getErrorString("null", "AmqpTransportType"));
}
try {
return TransportType.valueOf(s);
} catch (IllegalArgumentException e) {
throw new ParameterException(getErrorString(s, "AmqpTransportType"), e);
}
} | throw new ParameterException(getErrorString("null", "AmqpTransportType")); | public TransportType convert(String s) {
if (s == null) {
throw new ParameterException(getErrorString("null", "AmqpTransportType"));
}
try {
return TransportType.valueOf(s);
} catch (IllegalArgumentException e) {
throw new ParameterException(getErrorString(s, "AmqpTransportType"), e);
}
} | class TransportTypeConverter extends BaseConverter<TransportType> {
public TransportTypeConverter(String optionName) {
super(optionName);
}
@Override
} | class TransportTypeConverter extends BaseConverter<TransportType> {
public TransportTypeConverter(String optionName) {
super(optionName);
}
@Override
} |
`/1_000_000_000.0` might be easier to count the number of zeros | private String getResults(int index, EventsCounter eventsCounter) {
final double seconds = eventsCounter.elapsedTime() * 0.000000001;
final double operationsSecond = eventsCounter.totalEvents() / seconds;
return String.format(FORMAT_STRING, eventsCounter.getPartitionId(), index,
eventsCounter.totalEvents(), eventsCounter.elapsedTime(), seconds, operationsSecond);
} | final double seconds = eventsCounter.elapsedTime() * 0.000000001; | private String getResults(int index, EventsCounter eventsCounter) {
final double seconds = eventsCounter.elapsedTime() * 0.000000001;
final double operationsSecond = eventsCounter.totalEvents() / seconds;
return String.format(FORMAT_STRING, eventsCounter.getPartitionId(), index,
eventsCounter.totalEvents(), eventsCounter.elapsedTime(), seconds, operationsSecond);
} | class EventProcessorTest extends ServiceTest<EventProcessorOptions> {
private static final String HEADERS = String.join("\t", "Id", "Index", "Count",
"Elapsed Time (ns)", "Elapsed Time (s)", "Rate (ops/sec)");
private static final String FORMAT_STRING = "%s\t%d\t%d\t%s\t%s\t%.2f";
private static final int MINIMUM_DURATION = 2 * 60;
private final ConcurrentHashMap<String, SamplePartitionProcessor> partitionProcessorMap;
private final Duration testDuration;
private volatile long startTime;
private volatile long endTime;
private BlobContainerAsyncClient containerClient;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
public EventProcessorTest(EventProcessorOptions options) {
super(options);
partitionProcessorMap = new ConcurrentHashMap<>();
testDuration = Duration.ofSeconds(options.getDuration() - 1);
}
@Override
public Mono<Void> globalSetupAsync() {
if (options.getDuration() < MINIMUM_DURATION) {
return Mono.error(new RuntimeException(
"Test duration is too short. It should be at least " + MINIMUM_DURATION + " seconds"));
}
final String containerName = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHMMss"));
containerClient = new BlobContainerClientBuilder()
.connectionString(options.getStorageConnectionString())
.containerName(containerName)
.buildAsyncClient();
final Mono<Void> createContainerMono = containerClient.exists().flatMap(exists -> {
if (exists) {
return containerClient.delete().then(containerClient.create());
} else {
return containerClient.create();
}
});
return Mono.using(
() -> createEventHubClientBuilder().buildAsyncProducerClient(),
asyncClient -> {
final Mono<Void> sendMessagesMono = asyncClient.getEventHubProperties()
.flatMapMany(properties -> {
for (String partitionId : properties.getPartitionIds()) {
partitionProcessorMap.put(partitionId, new SamplePartitionProcessor());
}
return Flux.fromIterable(properties.getPartitionIds());
})
.then();
return Mono.when(createContainerMono, sendMessagesMono);
},
asyncClient -> asyncClient.close());
}
@Override
public void run() {
runAsync().block();
}
@Override
public Mono<Void> runAsync() {
if (containerClient == null) {
return Mono.error(new RuntimeException("ContainerClient should have been initialized."));
}
return Mono.using(
() -> {
System.out.println("Starting run.");
final BlobCheckpointStore checkpointStore = new BlobCheckpointStore(containerClient);
final EventProcessorClientBuilder builder = new EventProcessorClientBuilder()
.connectionString(options.getConnectionString(), options.getEventHubName())
.consumerGroup(options.getConsumerGroup())
.loadBalancingStrategy(LoadBalancingStrategy.GREEDY)
.checkpointStore(checkpointStore)
.processError(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onError: %s%n",
partitionId, context.getThrowable());
} else {
processor.onError(context.getPartitionContext(), context.getThrowable());
}
})
.processPartitionInitialization(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onOpen%n", partitionId);
} else {
processor.onOpen(context.getPartitionContext());
}
})
.processPartitionClose(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onClose%n", partitionId);
} else {
processor.onClose(context.getPartitionContext(), context.getCloseReason());
}
});
if (options.isBatched()) {
if (options.getBatchSize() < 1) {
throw new RuntimeException("Batch size is invalid. " + options.getBatchSize());
}
builder.processEventBatch(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEvents());
}
}, options.getBatchSize());
} else {
builder.processEvent(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEventData());
}
});
}
if (options.getTransportType() != null) {
builder.transportType(options.getTransportType());
}
return builder.buildEventProcessorClient();
},
processor -> {
startTime = System.nanoTime();
processor.start();
return Mono.when(Mono.delay(testDuration));
},
processor -> {
System.out.println("Completed run.");
endTime = System.nanoTime();
processor.stop();
});
}
@Override
public Mono<Void> globalCleanupAsync() {
System.out.println("Cleaning up.");
if (containerClient != null) {
final BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("results.txt");
final ArrayList<ByteBuffer> byteBuffers = new ArrayList<>();
final ParallelTransferOptions options = new ParallelTransferOptions().setMaxConcurrency(4);
outputPartitionResults(content -> {
System.out.println(content);
byteBuffers.add(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
});
return blobAsyncClient.upload(Flux.fromIterable(byteBuffers), options)
.then()
.doFinally(signal -> System.out.println("Done global clean up."));
} else {
outputPartitionResults(System.out::println);
System.out.println("Done global clean up.");
return Mono.empty();
}
}
private void outputPartitionResults(Consumer<String> onOutput) {
onOutput.accept(HEADERS);
long total = 0;
for (SamplePartitionProcessor processor : partitionProcessorMap.values()) {
processor.onStop();
final List<EventsCounter> counters = processor.getCounters();
for (int i = 0; i < counters.size(); i++) {
final EventsCounter eventsCounter = counters.get(i);
total += eventsCounter.totalEvents();
final String result = getResults(i, eventsCounter);
onOutput.accept(result);
}
}
double elapsedTime = (endTime - startTime) * 0.000000001;
double eventsPerSecond = total / elapsedTime;
onOutput.accept("");
onOutput.accept(String.format("Total Events\t%d%n", total));
onOutput.accept(String.format("Total Duration (s)\t%.2f%n", elapsedTime));
onOutput.accept(String.format("Rate (events/s)\t%.2f%n", eventsPerSecond));
}
} | class EventProcessorTest extends ServiceTest<EventProcessorOptions> {
private static final String HEADERS = String.join("\t", "Id", "Index", "Count",
"Elapsed Time (ns)", "Elapsed Time (s)", "Rate (ops/sec)");
private static final String FORMAT_STRING = "%s\t%d\t%d\t%s\t%s\t%.2f";
private static final int MINIMUM_DURATION = 2 * 60;
private final ConcurrentHashMap<String, SamplePartitionProcessor> partitionProcessorMap;
private final Duration testDuration;
private volatile long startTime;
private volatile long endTime;
private BlobContainerAsyncClient containerClient;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
public EventProcessorTest(EventProcessorOptions options) {
super(options);
partitionProcessorMap = new ConcurrentHashMap<>();
testDuration = Duration.ofSeconds(options.getDuration() - 1);
}
@Override
public Mono<Void> globalSetupAsync() {
if (options.getDuration() < MINIMUM_DURATION) {
return Mono.error(new RuntimeException(
"Test duration is too short. It should be at least " + MINIMUM_DURATION + " seconds"));
}
final String containerName = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss"));
containerClient = new BlobContainerClientBuilder()
.connectionString(options.getStorageConnectionString())
.containerName(containerName)
.buildAsyncClient();
final Mono<Void> createContainerMono = containerClient.exists().flatMap(exists -> {
if (exists) {
return containerClient.delete().then(containerClient.create());
} else {
return containerClient.create();
}
});
return Mono.using(
() -> createEventHubClientBuilder().buildAsyncProducerClient(),
asyncClient -> {
final Mono<Void> sendMessagesMono = asyncClient.getEventHubProperties()
.flatMapMany(properties -> {
for (String partitionId : properties.getPartitionIds()) {
partitionProcessorMap.put(partitionId, new SamplePartitionProcessor());
}
return Flux.fromIterable(properties.getPartitionIds());
})
.flatMap(partitionId -> {
if (options.publishMessages()) {
return sendMessages(asyncClient, partitionId, options.getEventsToSend());
} else {
return Mono.empty();
}
})
.then();
return Mono.when(createContainerMono, sendMessagesMono);
},
EventHubProducerAsyncClient::close);
}
@Override
public void run() {
runAsync().block();
}
@Override
public Mono<Void> runAsync() {
if (containerClient == null) {
return Mono.error(new RuntimeException("ContainerClient should have been initialized."));
}
return Mono.usingWhen(
Mono.fromCallable(() -> {
System.out.println("Starting run.");
final BlobCheckpointStore checkpointStore = new BlobCheckpointStore(containerClient);
final EventProcessorClientBuilder builder = new EventProcessorClientBuilder()
.connectionString(options.getConnectionString(), options.getEventHubName())
.consumerGroup(options.getConsumerGroup())
.loadBalancingStrategy(LoadBalancingStrategy.GREEDY)
.checkpointStore(checkpointStore)
.processError(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onError: %s%n",
partitionId, context.getThrowable());
} else {
processor.onError(context.getPartitionContext(), context.getThrowable());
}
})
.processPartitionInitialization(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onOpen%n", partitionId);
} else {
processor.onOpen(context.getPartitionContext());
}
})
.processPartitionClose(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onClose%n", partitionId);
} else {
processor.onClose(context.getPartitionContext(), context.getCloseReason());
}
});
if (options.isBatched()) {
if (options.getBatchSize() < 1) {
throw new RuntimeException("Batch size is invalid. " + options.getBatchSize());
}
builder.processEventBatch(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEvents());
}
}, options.getBatchSize());
} else {
builder.processEvent(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEventData());
}
});
}
if (options.getTransportType() != null) {
builder.transportType(options.getTransportType());
}
return builder.buildEventProcessorClient();
}),
processor -> {
startTime = System.nanoTime();
processor.start();
return Mono.delay(testDuration).then();
},
processor -> {
System.out.println("Completed run.");
endTime = System.nanoTime();
return Mono.delay(Duration.ofMillis(500), Schedulers.boundedElastic())
.then(Mono.fromRunnable(() -> processor.stop()));
});
}
@Override
public Mono<Void> globalCleanupAsync() {
System.out.println("Cleaning up.");
if (containerClient != null) {
final BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("results.txt");
final ArrayList<ByteBuffer> byteBuffers = new ArrayList<>();
final ParallelTransferOptions options = new ParallelTransferOptions().setMaxConcurrency(4);
outputPartitionResults(content -> {
System.out.println(content);
byteBuffers.add(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
});
return blobAsyncClient.upload(Flux.fromIterable(byteBuffers), options)
.then()
.doFinally(signal -> System.out.println("Done global clean up."));
} else {
outputPartitionResults(System.out::println);
System.out.println("Done global clean up.");
return Mono.empty();
}
}
private void outputPartitionResults(Consumer<String> onOutput) {
onOutput.accept(HEADERS);
long total = 0;
for (SamplePartitionProcessor processor : partitionProcessorMap.values()) {
processor.onStop();
final List<EventsCounter> counters = processor.getCounters();
for (int i = 0; i < counters.size(); i++) {
final EventsCounter eventsCounter = counters.get(i);
total += eventsCounter.totalEvents();
final String result = getResults(i, eventsCounter);
onOutput.accept(result);
}
}
double elapsedTime = (endTime - startTime) * 0.000000001;
double eventsPerSecond = total / elapsedTime;
onOutput.accept("");
onOutput.accept(String.format("Total Events\t%d%n", total));
onOutput.accept(String.format("Total Duration (s)\t%.2f%n", elapsedTime));
onOutput.accept(String.format("Rate (events/s)\t%.2f%n", eventsPerSecond));
}
} |
Is it possible to use a map instead of a concurrent one to reduce some overhead? After you populate the map in the setup, the multi-thread code only use get. Disregard this question if the overhead is very small. I didn't test. | public EventProcessorTest(EventProcessorOptions options) {
super(options);
partitionProcessorMap = new ConcurrentHashMap<>();
testDuration = Duration.ofSeconds(options.getDuration() - 1);
} | partitionProcessorMap = new ConcurrentHashMap<>(); | public EventProcessorTest(EventProcessorOptions options) {
super(options);
partitionProcessorMap = new ConcurrentHashMap<>();
testDuration = Duration.ofSeconds(options.getDuration() - 1);
} | class EventProcessorTest extends ServiceTest<EventProcessorOptions> {
private static final String HEADERS = String.join("\t", "Id", "Index", "Count",
"Elapsed Time (ns)", "Elapsed Time (s)", "Rate (ops/sec)");
private static final String FORMAT_STRING = "%s\t%d\t%d\t%s\t%s\t%.2f";
private static final int MINIMUM_DURATION = 2 * 60;
private final ConcurrentHashMap<String, SamplePartitionProcessor> partitionProcessorMap;
private final Duration testDuration;
private volatile long startTime;
private volatile long endTime;
private BlobContainerAsyncClient containerClient;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
@Override
public Mono<Void> globalSetupAsync() {
if (options.getDuration() < MINIMUM_DURATION) {
return Mono.error(new RuntimeException(
"Test duration is too short. It should be at least " + MINIMUM_DURATION + " seconds"));
}
final String containerName = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHMMss"));
containerClient = new BlobContainerClientBuilder()
.connectionString(options.getStorageConnectionString())
.containerName(containerName)
.buildAsyncClient();
final Mono<Void> createContainerMono = containerClient.exists().flatMap(exists -> {
if (exists) {
return containerClient.delete().then(containerClient.create());
} else {
return containerClient.create();
}
});
return Mono.using(
() -> createEventHubClientBuilder().buildAsyncProducerClient(),
asyncClient -> {
final Mono<Void> sendMessagesMono = asyncClient.getEventHubProperties()
.flatMapMany(properties -> {
for (String partitionId : properties.getPartitionIds()) {
partitionProcessorMap.put(partitionId, new SamplePartitionProcessor());
}
return Flux.fromIterable(properties.getPartitionIds());
})
.then();
return Mono.when(createContainerMono, sendMessagesMono);
},
asyncClient -> asyncClient.close());
}
@Override
public void run() {
runAsync().block();
}
@Override
public Mono<Void> runAsync() {
if (containerClient == null) {
return Mono.error(new RuntimeException("ContainerClient should have been initialized."));
}
return Mono.using(
() -> {
System.out.println("Starting run.");
final BlobCheckpointStore checkpointStore = new BlobCheckpointStore(containerClient);
final EventProcessorClientBuilder builder = new EventProcessorClientBuilder()
.connectionString(options.getConnectionString(), options.getEventHubName())
.consumerGroup(options.getConsumerGroup())
.loadBalancingStrategy(LoadBalancingStrategy.GREEDY)
.checkpointStore(checkpointStore)
.processError(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onError: %s%n",
partitionId, context.getThrowable());
} else {
processor.onError(context.getPartitionContext(), context.getThrowable());
}
})
.processPartitionInitialization(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onOpen%n", partitionId);
} else {
processor.onOpen(context.getPartitionContext());
}
})
.processPartitionClose(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onClose%n", partitionId);
} else {
processor.onClose(context.getPartitionContext(), context.getCloseReason());
}
});
if (options.isBatched()) {
if (options.getBatchSize() < 1) {
throw new RuntimeException("Batch size is invalid. " + options.getBatchSize());
}
builder.processEventBatch(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEvents());
}
}, options.getBatchSize());
} else {
builder.processEvent(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEventData());
}
});
}
if (options.getTransportType() != null) {
builder.transportType(options.getTransportType());
}
return builder.buildEventProcessorClient();
},
processor -> {
startTime = System.nanoTime();
processor.start();
return Mono.when(Mono.delay(testDuration));
},
processor -> {
System.out.println("Completed run.");
endTime = System.nanoTime();
processor.stop();
});
}
@Override
public Mono<Void> globalCleanupAsync() {
System.out.println("Cleaning up.");
if (containerClient != null) {
final BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("results.txt");
final ArrayList<ByteBuffer> byteBuffers = new ArrayList<>();
final ParallelTransferOptions options = new ParallelTransferOptions().setMaxConcurrency(4);
outputPartitionResults(content -> {
System.out.println(content);
byteBuffers.add(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
});
return blobAsyncClient.upload(Flux.fromIterable(byteBuffers), options)
.then()
.doFinally(signal -> System.out.println("Done global clean up."));
} else {
outputPartitionResults(System.out::println);
System.out.println("Done global clean up.");
return Mono.empty();
}
}
private void outputPartitionResults(Consumer<String> onOutput) {
onOutput.accept(HEADERS);
long total = 0;
for (SamplePartitionProcessor processor : partitionProcessorMap.values()) {
processor.onStop();
final List<EventsCounter> counters = processor.getCounters();
for (int i = 0; i < counters.size(); i++) {
final EventsCounter eventsCounter = counters.get(i);
total += eventsCounter.totalEvents();
final String result = getResults(i, eventsCounter);
onOutput.accept(result);
}
}
double elapsedTime = (endTime - startTime) * 0.000000001;
double eventsPerSecond = total / elapsedTime;
onOutput.accept("");
onOutput.accept(String.format("Total Events\t%d%n", total));
onOutput.accept(String.format("Total Duration (s)\t%.2f%n", elapsedTime));
onOutput.accept(String.format("Rate (events/s)\t%.2f%n", eventsPerSecond));
}
private String getResults(int index, EventsCounter eventsCounter) {
final double seconds = eventsCounter.elapsedTime() * 0.000000001;
final double operationsSecond = eventsCounter.totalEvents() / seconds;
return String.format(FORMAT_STRING, eventsCounter.getPartitionId(), index,
eventsCounter.totalEvents(), eventsCounter.elapsedTime(), seconds, operationsSecond);
}
} | class EventProcessorTest extends ServiceTest<EventProcessorOptions> {
private static final String HEADERS = String.join("\t", "Id", "Index", "Count",
"Elapsed Time (ns)", "Elapsed Time (s)", "Rate (ops/sec)");
private static final String FORMAT_STRING = "%s\t%d\t%d\t%s\t%s\t%.2f";
private static final int MINIMUM_DURATION = 2 * 60;
private final ConcurrentHashMap<String, SamplePartitionProcessor> partitionProcessorMap;
private final Duration testDuration;
private volatile long startTime;
private volatile long endTime;
private BlobContainerAsyncClient containerClient;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
@Override
public Mono<Void> globalSetupAsync() {
if (options.getDuration() < MINIMUM_DURATION) {
return Mono.error(new RuntimeException(
"Test duration is too short. It should be at least " + MINIMUM_DURATION + " seconds"));
}
final String containerName = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss"));
containerClient = new BlobContainerClientBuilder()
.connectionString(options.getStorageConnectionString())
.containerName(containerName)
.buildAsyncClient();
final Mono<Void> createContainerMono = containerClient.exists().flatMap(exists -> {
if (exists) {
return containerClient.delete().then(containerClient.create());
} else {
return containerClient.create();
}
});
return Mono.using(
() -> createEventHubClientBuilder().buildAsyncProducerClient(),
asyncClient -> {
final Mono<Void> sendMessagesMono = asyncClient.getEventHubProperties()
.flatMapMany(properties -> {
for (String partitionId : properties.getPartitionIds()) {
partitionProcessorMap.put(partitionId, new SamplePartitionProcessor());
}
return Flux.fromIterable(properties.getPartitionIds());
})
.flatMap(partitionId -> {
if (options.publishMessages()) {
return sendMessages(asyncClient, partitionId, options.getEventsToSend());
} else {
return Mono.empty();
}
})
.then();
return Mono.when(createContainerMono, sendMessagesMono);
},
EventHubProducerAsyncClient::close);
}
@Override
public void run() {
runAsync().block();
}
@Override
public Mono<Void> runAsync() {
if (containerClient == null) {
return Mono.error(new RuntimeException("ContainerClient should have been initialized."));
}
return Mono.usingWhen(
Mono.fromCallable(() -> {
System.out.println("Starting run.");
final BlobCheckpointStore checkpointStore = new BlobCheckpointStore(containerClient);
final EventProcessorClientBuilder builder = new EventProcessorClientBuilder()
.connectionString(options.getConnectionString(), options.getEventHubName())
.consumerGroup(options.getConsumerGroup())
.loadBalancingStrategy(LoadBalancingStrategy.GREEDY)
.checkpointStore(checkpointStore)
.processError(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onError: %s%n",
partitionId, context.getThrowable());
} else {
processor.onError(context.getPartitionContext(), context.getThrowable());
}
})
.processPartitionInitialization(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onOpen%n", partitionId);
} else {
processor.onOpen(context.getPartitionContext());
}
})
.processPartitionClose(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onClose%n", partitionId);
} else {
processor.onClose(context.getPartitionContext(), context.getCloseReason());
}
});
if (options.isBatched()) {
if (options.getBatchSize() < 1) {
throw new RuntimeException("Batch size is invalid. " + options.getBatchSize());
}
builder.processEventBatch(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEvents());
}
}, options.getBatchSize());
} else {
builder.processEvent(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEventData());
}
});
}
if (options.getTransportType() != null) {
builder.transportType(options.getTransportType());
}
return builder.buildEventProcessorClient();
}),
processor -> {
startTime = System.nanoTime();
processor.start();
return Mono.delay(testDuration).then();
},
processor -> {
System.out.println("Completed run.");
endTime = System.nanoTime();
return Mono.delay(Duration.ofMillis(500), Schedulers.boundedElastic())
.then(Mono.fromRunnable(() -> processor.stop()));
});
}
@Override
public Mono<Void> globalCleanupAsync() {
System.out.println("Cleaning up.");
if (containerClient != null) {
final BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("results.txt");
final ArrayList<ByteBuffer> byteBuffers = new ArrayList<>();
final ParallelTransferOptions options = new ParallelTransferOptions().setMaxConcurrency(4);
outputPartitionResults(content -> {
System.out.println(content);
byteBuffers.add(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
});
return blobAsyncClient.upload(Flux.fromIterable(byteBuffers), options)
.then()
.doFinally(signal -> System.out.println("Done global clean up."));
} else {
outputPartitionResults(System.out::println);
System.out.println("Done global clean up.");
return Mono.empty();
}
}
private void outputPartitionResults(Consumer<String> onOutput) {
onOutput.accept(HEADERS);
long total = 0;
for (SamplePartitionProcessor processor : partitionProcessorMap.values()) {
processor.onStop();
final List<EventsCounter> counters = processor.getCounters();
for (int i = 0; i < counters.size(); i++) {
final EventsCounter eventsCounter = counters.get(i);
total += eventsCounter.totalEvents();
final String result = getResults(i, eventsCounter);
onOutput.accept(result);
}
}
double elapsedTime = (endTime - startTime) * 0.000000001;
double eventsPerSecond = total / elapsedTime;
onOutput.accept("");
onOutput.accept(String.format("Total Events\t%d%n", total));
onOutput.accept(String.format("Total Duration (s)\t%.2f%n", elapsedTime));
onOutput.accept(String.format("Rate (events/s)\t%.2f%n", eventsPerSecond));
}
private String getResults(int index, EventsCounter eventsCounter) {
final double seconds = eventsCounter.elapsedTime() * 0.000000001;
final double operationsSecond = eventsCounter.totalEvents() / seconds;
return String.format(FORMAT_STRING, eventsCounter.getPartitionId(), index,
eventsCounter.totalEvents(), eventsCounter.elapsedTime(), seconds, operationsSecond);
}
} |
Ahh yeah. I always thought multiplication was faster for processors than division. But maybe this is moot now. | private String getResults(int index, EventsCounter eventsCounter) {
final double seconds = eventsCounter.elapsedTime() * 0.000000001;
final double operationsSecond = eventsCounter.totalEvents() / seconds;
return String.format(FORMAT_STRING, eventsCounter.getPartitionId(), index,
eventsCounter.totalEvents(), eventsCounter.elapsedTime(), seconds, operationsSecond);
} | final double seconds = eventsCounter.elapsedTime() * 0.000000001; | private String getResults(int index, EventsCounter eventsCounter) {
final double seconds = eventsCounter.elapsedTime() * 0.000000001;
final double operationsSecond = eventsCounter.totalEvents() / seconds;
return String.format(FORMAT_STRING, eventsCounter.getPartitionId(), index,
eventsCounter.totalEvents(), eventsCounter.elapsedTime(), seconds, operationsSecond);
} | class EventProcessorTest extends ServiceTest<EventProcessorOptions> {
private static final String HEADERS = String.join("\t", "Id", "Index", "Count",
"Elapsed Time (ns)", "Elapsed Time (s)", "Rate (ops/sec)");
private static final String FORMAT_STRING = "%s\t%d\t%d\t%s\t%s\t%.2f";
private static final int MINIMUM_DURATION = 2 * 60;
private final ConcurrentHashMap<String, SamplePartitionProcessor> partitionProcessorMap;
private final Duration testDuration;
private volatile long startTime;
private volatile long endTime;
private BlobContainerAsyncClient containerClient;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
public EventProcessorTest(EventProcessorOptions options) {
super(options);
partitionProcessorMap = new ConcurrentHashMap<>();
testDuration = Duration.ofSeconds(options.getDuration() - 1);
}
@Override
public Mono<Void> globalSetupAsync() {
if (options.getDuration() < MINIMUM_DURATION) {
return Mono.error(new RuntimeException(
"Test duration is too short. It should be at least " + MINIMUM_DURATION + " seconds"));
}
final String containerName = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHMMss"));
containerClient = new BlobContainerClientBuilder()
.connectionString(options.getStorageConnectionString())
.containerName(containerName)
.buildAsyncClient();
final Mono<Void> createContainerMono = containerClient.exists().flatMap(exists -> {
if (exists) {
return containerClient.delete().then(containerClient.create());
} else {
return containerClient.create();
}
});
return Mono.using(
() -> createEventHubClientBuilder().buildAsyncProducerClient(),
asyncClient -> {
final Mono<Void> sendMessagesMono = asyncClient.getEventHubProperties()
.flatMapMany(properties -> {
for (String partitionId : properties.getPartitionIds()) {
partitionProcessorMap.put(partitionId, new SamplePartitionProcessor());
}
return Flux.fromIterable(properties.getPartitionIds());
})
.then();
return Mono.when(createContainerMono, sendMessagesMono);
},
asyncClient -> asyncClient.close());
}
@Override
public void run() {
runAsync().block();
}
@Override
public Mono<Void> runAsync() {
if (containerClient == null) {
return Mono.error(new RuntimeException("ContainerClient should have been initialized."));
}
return Mono.using(
() -> {
System.out.println("Starting run.");
final BlobCheckpointStore checkpointStore = new BlobCheckpointStore(containerClient);
final EventProcessorClientBuilder builder = new EventProcessorClientBuilder()
.connectionString(options.getConnectionString(), options.getEventHubName())
.consumerGroup(options.getConsumerGroup())
.loadBalancingStrategy(LoadBalancingStrategy.GREEDY)
.checkpointStore(checkpointStore)
.processError(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onError: %s%n",
partitionId, context.getThrowable());
} else {
processor.onError(context.getPartitionContext(), context.getThrowable());
}
})
.processPartitionInitialization(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onOpen%n", partitionId);
} else {
processor.onOpen(context.getPartitionContext());
}
})
.processPartitionClose(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onClose%n", partitionId);
} else {
processor.onClose(context.getPartitionContext(), context.getCloseReason());
}
});
if (options.isBatched()) {
if (options.getBatchSize() < 1) {
throw new RuntimeException("Batch size is invalid. " + options.getBatchSize());
}
builder.processEventBatch(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEvents());
}
}, options.getBatchSize());
} else {
builder.processEvent(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEventData());
}
});
}
if (options.getTransportType() != null) {
builder.transportType(options.getTransportType());
}
return builder.buildEventProcessorClient();
},
processor -> {
startTime = System.nanoTime();
processor.start();
return Mono.when(Mono.delay(testDuration));
},
processor -> {
System.out.println("Completed run.");
endTime = System.nanoTime();
processor.stop();
});
}
@Override
public Mono<Void> globalCleanupAsync() {
System.out.println("Cleaning up.");
if (containerClient != null) {
final BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("results.txt");
final ArrayList<ByteBuffer> byteBuffers = new ArrayList<>();
final ParallelTransferOptions options = new ParallelTransferOptions().setMaxConcurrency(4);
outputPartitionResults(content -> {
System.out.println(content);
byteBuffers.add(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
});
return blobAsyncClient.upload(Flux.fromIterable(byteBuffers), options)
.then()
.doFinally(signal -> System.out.println("Done global clean up."));
} else {
outputPartitionResults(System.out::println);
System.out.println("Done global clean up.");
return Mono.empty();
}
}
private void outputPartitionResults(Consumer<String> onOutput) {
onOutput.accept(HEADERS);
long total = 0;
for (SamplePartitionProcessor processor : partitionProcessorMap.values()) {
processor.onStop();
final List<EventsCounter> counters = processor.getCounters();
for (int i = 0; i < counters.size(); i++) {
final EventsCounter eventsCounter = counters.get(i);
total += eventsCounter.totalEvents();
final String result = getResults(i, eventsCounter);
onOutput.accept(result);
}
}
double elapsedTime = (endTime - startTime) * 0.000000001;
double eventsPerSecond = total / elapsedTime;
onOutput.accept("");
onOutput.accept(String.format("Total Events\t%d%n", total));
onOutput.accept(String.format("Total Duration (s)\t%.2f%n", elapsedTime));
onOutput.accept(String.format("Rate (events/s)\t%.2f%n", eventsPerSecond));
}
} | class EventProcessorTest extends ServiceTest<EventProcessorOptions> {
private static final String HEADERS = String.join("\t", "Id", "Index", "Count",
"Elapsed Time (ns)", "Elapsed Time (s)", "Rate (ops/sec)");
private static final String FORMAT_STRING = "%s\t%d\t%d\t%s\t%s\t%.2f";
private static final int MINIMUM_DURATION = 2 * 60;
private final ConcurrentHashMap<String, SamplePartitionProcessor> partitionProcessorMap;
private final Duration testDuration;
private volatile long startTime;
private volatile long endTime;
private BlobContainerAsyncClient containerClient;
/**
* Creates an instance of performance test.
*
* @param options the options configured for the test.
*/
public EventProcessorTest(EventProcessorOptions options) {
super(options);
partitionProcessorMap = new ConcurrentHashMap<>();
testDuration = Duration.ofSeconds(options.getDuration() - 1);
}
@Override
public Mono<Void> globalSetupAsync() {
if (options.getDuration() < MINIMUM_DURATION) {
return Mono.error(new RuntimeException(
"Test duration is too short. It should be at least " + MINIMUM_DURATION + " seconds"));
}
final String containerName = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss"));
containerClient = new BlobContainerClientBuilder()
.connectionString(options.getStorageConnectionString())
.containerName(containerName)
.buildAsyncClient();
final Mono<Void> createContainerMono = containerClient.exists().flatMap(exists -> {
if (exists) {
return containerClient.delete().then(containerClient.create());
} else {
return containerClient.create();
}
});
return Mono.using(
() -> createEventHubClientBuilder().buildAsyncProducerClient(),
asyncClient -> {
final Mono<Void> sendMessagesMono = asyncClient.getEventHubProperties()
.flatMapMany(properties -> {
for (String partitionId : properties.getPartitionIds()) {
partitionProcessorMap.put(partitionId, new SamplePartitionProcessor());
}
return Flux.fromIterable(properties.getPartitionIds());
})
.flatMap(partitionId -> {
if (options.publishMessages()) {
return sendMessages(asyncClient, partitionId, options.getEventsToSend());
} else {
return Mono.empty();
}
})
.then();
return Mono.when(createContainerMono, sendMessagesMono);
},
EventHubProducerAsyncClient::close);
}
@Override
public void run() {
runAsync().block();
}
@Override
public Mono<Void> runAsync() {
if (containerClient == null) {
return Mono.error(new RuntimeException("ContainerClient should have been initialized."));
}
return Mono.usingWhen(
Mono.fromCallable(() -> {
System.out.println("Starting run.");
final BlobCheckpointStore checkpointStore = new BlobCheckpointStore(containerClient);
final EventProcessorClientBuilder builder = new EventProcessorClientBuilder()
.connectionString(options.getConnectionString(), options.getEventHubName())
.consumerGroup(options.getConsumerGroup())
.loadBalancingStrategy(LoadBalancingStrategy.GREEDY)
.checkpointStore(checkpointStore)
.processError(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onError: %s%n",
partitionId, context.getThrowable());
} else {
processor.onError(context.getPartitionContext(), context.getThrowable());
}
})
.processPartitionInitialization(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onOpen%n", partitionId);
} else {
processor.onOpen(context.getPartitionContext());
}
})
.processPartitionClose(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onClose%n", partitionId);
} else {
processor.onClose(context.getPartitionContext(), context.getCloseReason());
}
});
if (options.isBatched()) {
if (options.getBatchSize() < 1) {
throw new RuntimeException("Batch size is invalid. " + options.getBatchSize());
}
builder.processEventBatch(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEvents());
}
}, options.getBatchSize());
} else {
builder.processEvent(context -> {
final String partitionId = context.getPartitionContext().getPartitionId();
final SamplePartitionProcessor processor = partitionProcessorMap.get(partitionId);
if (processor == null) {
System.err.printf("partitionId: %s. No matching processor. onEvent%n", partitionId);
} else {
processor.onEvents(context.getPartitionContext(), context.getEventData());
}
});
}
if (options.getTransportType() != null) {
builder.transportType(options.getTransportType());
}
return builder.buildEventProcessorClient();
}),
processor -> {
startTime = System.nanoTime();
processor.start();
return Mono.delay(testDuration).then();
},
processor -> {
System.out.println("Completed run.");
endTime = System.nanoTime();
return Mono.delay(Duration.ofMillis(500), Schedulers.boundedElastic())
.then(Mono.fromRunnable(() -> processor.stop()));
});
}
@Override
public Mono<Void> globalCleanupAsync() {
System.out.println("Cleaning up.");
if (containerClient != null) {
final BlobAsyncClient blobAsyncClient = containerClient.getBlobAsyncClient("results.txt");
final ArrayList<ByteBuffer> byteBuffers = new ArrayList<>();
final ParallelTransferOptions options = new ParallelTransferOptions().setMaxConcurrency(4);
outputPartitionResults(content -> {
System.out.println(content);
byteBuffers.add(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
});
return blobAsyncClient.upload(Flux.fromIterable(byteBuffers), options)
.then()
.doFinally(signal -> System.out.println("Done global clean up."));
} else {
outputPartitionResults(System.out::println);
System.out.println("Done global clean up.");
return Mono.empty();
}
}
private void outputPartitionResults(Consumer<String> onOutput) {
onOutput.accept(HEADERS);
long total = 0;
for (SamplePartitionProcessor processor : partitionProcessorMap.values()) {
processor.onStop();
final List<EventsCounter> counters = processor.getCounters();
for (int i = 0; i < counters.size(); i++) {
final EventsCounter eventsCounter = counters.get(i);
total += eventsCounter.totalEvents();
final String result = getResults(i, eventsCounter);
onOutput.accept(result);
}
}
double elapsedTime = (endTime - startTime) * 0.000000001;
double eventsPerSecond = total / elapsedTime;
onOutput.accept("");
onOutput.accept(String.format("Total Events\t%d%n", total));
onOutput.accept(String.format("Total Duration (s)\t%.2f%n", elapsedTime));
onOutput.accept(String.format("Rate (events/s)\t%.2f%n", eventsPerSecond));
}
} |
The default is to use AmqpTransportType.AMQP. It only tries to parse this if you pass in the parameter `--transportType`. And if you didn't pass a value, I think that should be a user error because it's not what you expected. | public TransportType convert(String s) {
if (s == null) {
throw new ParameterException(getErrorString("null", "AmqpTransportType"));
}
try {
return TransportType.valueOf(s);
} catch (IllegalArgumentException e) {
throw new ParameterException(getErrorString(s, "AmqpTransportType"), e);
}
} | throw new ParameterException(getErrorString("null", "AmqpTransportType")); | public TransportType convert(String s) {
if (s == null) {
throw new ParameterException(getErrorString("null", "AmqpTransportType"));
}
try {
return TransportType.valueOf(s);
} catch (IllegalArgumentException e) {
throw new ParameterException(getErrorString(s, "AmqpTransportType"), e);
}
} | class TransportTypeConverter extends BaseConverter<TransportType> {
public TransportTypeConverter(String optionName) {
super(optionName);
}
@Override
} | class TransportTypeConverter extends BaseConverter<TransportType> {
public TransportTypeConverter(String optionName) {
super(optionName);
}
@Override
} |
1. Why we need this? 2. Can we always use `AccessController.doPrivileged` without checking `System.getSecurityManager() == null`? | private static String privilegedGetProperty(String theProp, String defaultVal) {
if (System.getSecurityManager() == null) {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
} else {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
} | return AccessController.doPrivileged( | private static String privilegedGetProperty(String theProp, String defaultVal) {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static void loadKeyStore(KeyStore ks) {
InputStream inStream = null;
try {
inStream = Files.newInputStream(getKeyStoreFile());
ks.load(inStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
} finally {
try {
inStream.close();
} catch (NullPointerException | IOException e) {
LOGGER.log(WARNING, "", e);
}
}
}
private static Path getKeyStoreFile() {
String storePropName = privilegedGetProperty(
"javax.net.ssl.keyStore", "");
return getStoreFile(storePropName);
}
private static Path getStoreFile(String storePropName) {
Path storeProp;
if (storePropName.isEmpty()) {
storeProp = JSSE_DEFAULT_STORE;
} else {
storeProp = Paths.get(storePropName);
}
Path[] fileNames = new Path[]{storeProp, DEFAULT_STORE};
return Arrays.stream(fileNames)
.filter(a -> Files.exists(a) && Files.isReadable(a))
.findFirst().orElse(null);
}
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static void loadKeyStore(KeyStore ks) {
try (InputStream inputStream = Files.newInputStream(getKeyStoreFile())) {
ks.load(inputStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
}
}
private static Path getKeyStoreFile() {
return Stream.of(getConfiguredKeyStorePath(), JSSE_DEFAULT_STORE, DEFAULT_STORE)
.filter(Objects::nonNull)
.filter(Files::exists)
.filter(Files::isReadable)
.findFirst()
.orElse(null);
}
private static Path getConfiguredKeyStorePath() {
String configuredKeyStorePath = privilegedGetProperty("javax.net.ssl.keyStore", "");
return Optional.of(configuredKeyStorePath)
.filter(path -> !path.isEmpty())
.map(Paths::get)
.orElse(null);
}
} |
Can we do like this: ``` private static void loadKeyStore(KeyStore ks) { try (InputStream inStream = Files.newInputStream(getKeyStoreFile())) { ks.load(inStream, KEY_STORE_PASSWORD.toCharArray()); } catch (IOException | NoSuchAlgorithmException | CertificateException e) { LOGGER.log(WARNING, "unable to load the jre key store", e); } } ``` | private static void loadKeyStore(KeyStore ks) {
InputStream inStream = null;
try {
inStream = Files.newInputStream(getKeyStoreFile());
ks.load(inStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
} finally {
try {
inStream.close();
} catch (NullPointerException | IOException e) {
LOGGER.log(WARNING, "", e);
}
}
} | } | private static void loadKeyStore(KeyStore ks) {
try (InputStream inputStream = Files.newInputStream(getKeyStoreFile())) {
ks.load(inputStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
}
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static Path getKeyStoreFile() {
String storePropName = privilegedGetProperty(
"javax.net.ssl.keyStore", "");
return getStoreFile(storePropName);
}
private static Path getStoreFile(String storePropName) {
Path storeProp;
if (storePropName.isEmpty()) {
storeProp = JSSE_DEFAULT_STORE;
} else {
storeProp = Paths.get(storePropName);
}
Path[] fileNames = new Path[]{storeProp, DEFAULT_STORE};
return Arrays.stream(fileNames)
.filter(a -> Files.exists(a) && Files.isReadable(a))
.findFirst().orElse(null);
}
private static String privilegedGetProperty(String theProp, String defaultVal) {
if (System.getSecurityManager() == null) {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
} else {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
}
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static Path getKeyStoreFile() {
return Stream.of(getConfiguredKeyStorePath(), JSSE_DEFAULT_STORE, DEFAULT_STORE)
.filter(Objects::nonNull)
.filter(Files::exists)
.filter(Files::isReadable)
.findFirst()
.orElse(null);
}
private static Path getConfiguredKeyStorePath() {
String configuredKeyStorePath = privilegedGetProperty("javax.net.ssl.keyStore", "");
return Optional.of(configuredKeyStorePath)
.filter(path -> !path.isEmpty())
.map(Paths::get)
.orElse(null);
}
private static String privilegedGetProperty(String theProp, String defaultVal) {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
} |
nit: Don't break line. | private static Path getKeyStoreFile() {
String storePropName = privilegedGetProperty(
"javax.net.ssl.keyStore", "");
return getStoreFile(storePropName);
} | "javax.net.ssl.keyStore", ""); | private static Path getKeyStoreFile() {
return Stream.of(getConfiguredKeyStorePath(), JSSE_DEFAULT_STORE, DEFAULT_STORE)
.filter(Objects::nonNull)
.filter(Files::exists)
.filter(Files::isReadable)
.findFirst()
.orElse(null);
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static void loadKeyStore(KeyStore ks) {
InputStream inStream = null;
try {
inStream = Files.newInputStream(getKeyStoreFile());
ks.load(inStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
} finally {
try {
inStream.close();
} catch (NullPointerException | IOException e) {
LOGGER.log(WARNING, "", e);
}
}
}
private static Path getStoreFile(String storePropName) {
Path storeProp;
if (storePropName.isEmpty()) {
storeProp = JSSE_DEFAULT_STORE;
} else {
storeProp = Paths.get(storePropName);
}
Path[] fileNames = new Path[]{storeProp, DEFAULT_STORE};
return Arrays.stream(fileNames)
.filter(a -> Files.exists(a) && Files.isReadable(a))
.findFirst().orElse(null);
}
private static String privilegedGetProperty(String theProp, String defaultVal) {
if (System.getSecurityManager() == null) {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
} else {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
}
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static void loadKeyStore(KeyStore ks) {
try (InputStream inputStream = Files.newInputStream(getKeyStoreFile())) {
ks.load(inputStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
}
}
private static Path getConfiguredKeyStorePath() {
String configuredKeyStorePath = privilegedGetProperty("javax.net.ssl.keyStore", "");
return Optional.of(configuredKeyStorePath)
.filter(path -> !path.isEmpty())
.map(Paths::get)
.orElse(null);
}
private static String privilegedGetProperty(String theProp, String defaultVal) {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
} |
checkstyle will complain with failures. " redundant non-null check." | private static void loadKeyStore(KeyStore ks) {
InputStream inStream = null;
try {
inStream = Files.newInputStream(getKeyStoreFile());
ks.load(inStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
} finally {
try {
inStream.close();
} catch (NullPointerException | IOException e) {
LOGGER.log(WARNING, "", e);
}
}
} | } | private static void loadKeyStore(KeyStore ks) {
try (InputStream inputStream = Files.newInputStream(getKeyStoreFile())) {
ks.load(inputStream, KEY_STORE_PASSWORD.toCharArray());
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
LOGGER.log(WARNING, "unable to load the jre key store", e);
}
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static Path getKeyStoreFile() {
String storePropName = privilegedGetProperty(
"javax.net.ssl.keyStore", "");
return getStoreFile(storePropName);
}
private static Path getStoreFile(String storePropName) {
Path storeProp;
if (storePropName.isEmpty()) {
storeProp = JSSE_DEFAULT_STORE;
} else {
storeProp = Paths.get(storePropName);
}
Path[] fileNames = new Path[]{storeProp, DEFAULT_STORE};
return Arrays.stream(fileNames)
.filter(a -> Files.exists(a) && Files.isReadable(a))
.findFirst().orElse(null);
}
private static String privilegedGetProperty(String theProp, String defaultVal) {
if (System.getSecurityManager() == null) {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
} else {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
}
} | class JREKeyStore {
private static final String JAVA_HOME = privilegedGetProperty("java.home", "");
private static final Path STORE_PATH = Paths.get(JAVA_HOME).resolve("lib").resolve("security");
private static final Path DEFAULT_STORE = STORE_PATH.resolve("cacerts");
private static final Path JSSE_DEFAULT_STORE = STORE_PATH.resolve("jssecacerts");
private static final String KEY_STORE_PASSWORD = privilegedGetProperty("javax.net.ssl.keyStorePassword", "changeit");
private static KeyStore getDefault() {
KeyStore defaultKeyStore = null;
try {
defaultKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(defaultKeyStore);
} catch (KeyStoreException e) {
LOGGER.log(WARNING, "Unable to get the jre key store.", e);
}
return defaultKeyStore;
}
private static Path getKeyStoreFile() {
return Stream.of(getConfiguredKeyStorePath(), JSSE_DEFAULT_STORE, DEFAULT_STORE)
.filter(Objects::nonNull)
.filter(Files::exists)
.filter(Files::isReadable)
.findFirst()
.orElse(null);
}
private static Path getConfiguredKeyStorePath() {
String configuredKeyStorePath = privilegedGetProperty("javax.net.ssl.keyStore", "");
return Optional.of(configuredKeyStorePath)
.filter(path -> !path.isEmpty())
.map(Paths::get)
.orElse(null);
}
private static String privilegedGetProperty(String theProp, String defaultVal) {
return AccessController.doPrivileged(
(PrivilegedAction<String>) () -> {
String value = System.getProperty(theProp, "");
return (value.isEmpty()) ? defaultVal : value;
});
}
} |
We might have to hide few properties from public API (such as secrets), we don't have the full list as we're waiting for the service team to confirm. We can do that once we get a response, not a blocker for this pr. | public String getClientSecret() {
return this.clientSecret;
} | } | public String getClientSecret() {
return this.clientSecret;
} | class AzureLogAnalyticsDataFeedSource extends DataFeedSource {
/*
* The tenant id of service principal that have access to this Log
* Analytics
*/
private final String tenantId;
/*
* The client id of service principal that have access to this Log
* Analytics
*/
private final String clientId;
/*
* The client secret of service principal that have access to this Log
* Analytics
*/
private final String clientSecret;
/*
* The workspace id of this Log Analytics
*/
private final String workspaceId;
/*
* The KQL (Kusto Query Language) query to fetch data from this Log
* Analytics
*/
private final String query;
/**
* Create a AzureLogAnalyticsDataFeedSource instance.
*
* @param tenantId The tenant id of service principal that have access to this Log Analytics.
* @param clientId The client id of service principal that have access to this Log Analytics.
* @param clientSecret The client secret of service principal that have access to this Log Analytics.
* @param workspaceId the query script.
* @param query the KQL (Kusto Query Language) query to fetch data from this Log
* Analytics.
*/
public AzureLogAnalyticsDataFeedSource(String tenantId, String clientId, String clientSecret,
String workspaceId, String query) {
this.tenantId = tenantId;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.workspaceId = workspaceId;
this.query = query;
}
/**
* Get the tenantId property: The tenant id of service principal that have access to this Log Analytics.
*
* @return the tenantId value.
*/
public String getTenantId() {
return this.tenantId;
}
/**
* Get the clientId property: The client id of service principal that have access to this Log Analytics.
*
* @return the clientId value.
*/
public String getClientId() {
return this.clientId;
}
/**
* Get the clientSecret property: The client secret of service principal that have access to this Log Analytics.
*
* @return the clientSecret value.
*/
/**
* Get the workspaceId property: The workspace id of this Log Analytics.
*
* @return the workspaceId value.
*/
public String getWorkspaceId() {
return this.workspaceId;
}
/**
* Get the query property: The KQL (Kusto Query Language) query to fetch data from this Log Analytics.
*
* @return the query value.
*/
public String getQuery() {
return this.query;
}
} | class AzureLogAnalyticsDataFeedSource extends DataFeedSource {
/*
* The tenant id of service principal that have access to this Log
* Analytics
*/
private final String tenantId;
/*
* The client id of service principal that have access to this Log
* Analytics
*/
private final String clientId;
/*
* The client secret of service principal that have access to this Log
* Analytics
*/
private final String clientSecret;
/*
* The workspace id of this Log Analytics
*/
private final String workspaceId;
/*
* The KQL (Kusto Query Language) query to fetch data from this Log
* Analytics
*/
private final String query;
/**
* Create a AzureLogAnalyticsDataFeedSource instance.
*
* @param tenantId The tenant id of service principal that have access to this Log Analytics.
* @param clientId The client id of service principal that have access to this Log Analytics.
* @param clientSecret The client secret of service principal that have access to this Log Analytics.
* @param workspaceId the query script.
* @param query the KQL (Kusto Query Language) query to fetch data from this Log
* Analytics.
*/
public AzureLogAnalyticsDataFeedSource(String tenantId, String clientId, String clientSecret,
String workspaceId, String query) {
this.tenantId = tenantId;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.workspaceId = workspaceId;
this.query = query;
}
/**
* Get the tenantId property: The tenant id of service principal that have access to this Log Analytics.
*
* @return the tenantId value.
*/
public String getTenantId() {
return this.tenantId;
}
/**
* Get the clientId property: The client id of service principal that have access to this Log Analytics.
*
* @return the clientId value.
*/
public String getClientId() {
return this.clientId;
}
/**
* Get the clientSecret property: The client secret of service principal that have access to this Log Analytics.
*
* @return the clientSecret value.
*/
/**
* Get the workspaceId property: The workspace id of this Log Analytics.
*
* @return the workspaceId value.
*/
public String getWorkspaceId() {
return this.workspaceId;
}
/**
* Get the query property: The KQL (Kusto Query Language) query to fetch data from this Log Analytics.
*
* @return the query value.
*/
public String getQuery() {
return this.query;
}
} |
Why are we going back in version? | public AzureCommunicationCallingServerServiceImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-28-preview0";
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
AzureCommunicationCallingServerServiceImpl client =
new AzureCommunicationCallingServerServiceImpl(pipeline, serializerAdapter, endpoint, apiVersion);
return client;
} | this.apiVersion = "2021-03-28-preview0"; | public AzureCommunicationCallingServerServiceImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-28-preview0";
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
AzureCommunicationCallingServerServiceImpl client =
new AzureCommunicationCallingServerServiceImpl(pipeline, serializerAdapter, endpoint, apiVersion);
return client;
} | class AzureCommunicationCallingServerServiceImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the AzureCommunicationCallingServerServiceImplBuilder. */
public AzureCommunicationCallingServerServiceImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The endpoint of the Azure Communication resource.
*/
private String endpoint;
/**
* Sets The endpoint of the Azure Communication resource.
*
* @param endpoint the endpoint value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of AzureCommunicationCallingServerServiceImpl with the provided parameters.
*
* @return an instance of AzureCommunicationCallingServerServiceImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} | class AzureCommunicationCallingServerServiceImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the AzureCommunicationCallingServerServiceImplBuilder. */
public AzureCommunicationCallingServerServiceImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The endpoint of the Azure Communication resource.
*/
private String endpoint;
/**
* Sets The endpoint of the Azure Communication resource.
*
* @param endpoint the endpoint value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of AzureCommunicationCallingServerServiceImpl with the provided parameters.
*
* @return an instance of AzureCommunicationCallingServerServiceImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} |
I changed the time to the date C# PR sent out. | public AzureCommunicationCallingServerServiceImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-28-preview0";
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
AzureCommunicationCallingServerServiceImpl client =
new AzureCommunicationCallingServerServiceImpl(pipeline, serializerAdapter, endpoint, apiVersion);
return client;
} | this.apiVersion = "2021-03-28-preview0"; | public AzureCommunicationCallingServerServiceImpl buildClient() {
if (apiVersion == null) {
this.apiVersion = "2021-03-28-preview0";
}
if (pipeline == null) {
this.pipeline = createHttpPipeline();
}
if (serializerAdapter == null) {
this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter();
}
AzureCommunicationCallingServerServiceImpl client =
new AzureCommunicationCallingServerServiceImpl(pipeline, serializerAdapter, endpoint, apiVersion);
return client;
} | class AzureCommunicationCallingServerServiceImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the AzureCommunicationCallingServerServiceImplBuilder. */
public AzureCommunicationCallingServerServiceImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The endpoint of the Azure Communication resource.
*/
private String endpoint;
/**
* Sets The endpoint of the Azure Communication resource.
*
* @param endpoint the endpoint value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of AzureCommunicationCallingServerServiceImpl with the provided parameters.
*
* @return an instance of AzureCommunicationCallingServerServiceImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} | class AzureCommunicationCallingServerServiceImplBuilder {
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final Map<String, String> properties = new HashMap<>();
/** Create an instance of the AzureCommunicationCallingServerServiceImplBuilder. */
public AzureCommunicationCallingServerServiceImplBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The endpoint of the Azure Communication resource.
*/
private String endpoint;
/**
* Sets The endpoint of the Azure Communication resource.
*
* @param endpoint the endpoint value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* Api Version
*/
private String apiVersion;
/**
* Sets Api Version.
*
* @param apiVersion the apiVersion value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/*
* The HTTP pipeline to send requests through
*/
private HttpPipeline pipeline;
/**
* Sets The HTTP pipeline to send requests through.
*
* @param pipeline the pipeline value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/*
* The serializer to serialize an object into a string
*/
private SerializerAdapter serializerAdapter;
/**
* Sets The serializer to serialize an object into a string.
*
* @param serializerAdapter the serializerAdapter value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
this.serializerAdapter = serializerAdapter;
return this;
}
/*
* The HTTP client used to send the request.
*/
private HttpClient httpClient;
/**
* Sets The HTTP client used to send the request.
*
* @param httpClient the httpClient value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The configuration store that is used during construction of the service
* client.
*/
private Configuration configuration;
/**
* Sets The configuration store that is used during construction of the service client.
*
* @param configuration the configuration value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
private HttpLogOptions httpLogOptions;
/**
* Sets The logging configuration for HTTP requests and responses.
*
* @param httpLogOptions the httpLogOptions value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if
* applicable.
*/
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/*
* The list of Http pipeline policies to add.
*/
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Adds a custom Http pipeline policy.
*
* @param customPolicy The custom Http pipeline policy to add.
* @return the AzureCommunicationCallingServerServiceImplBuilder.
*/
public AzureCommunicationCallingServerServiceImplBuilder addPolicy(HttpPipelinePolicy customPolicy) {
pipelinePolicies.add(customPolicy);
return this;
}
/**
* Builds an instance of AzureCommunicationCallingServerServiceImpl with the provided parameters.
*
* @return an instance of AzureCommunicationCallingServerServiceImpl.
*/
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration =
(configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
if (httpLogOptions == null) {
httpLogOptions = new HttpLogOptions();
}
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(
new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
policies.add(new CookiePolicy());
policies.addAll(this.pipelinePolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline httpPipeline =
new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
return httpPipeline;
}
} |
Same here. | public static String getFilePath() {
String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
} | String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\"; | public static String getFilePath() {
String filepath = "\\src\\test\\resources\\custom\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
} | class FileSystemCertificatesTest {
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} | class FileSystemCertificatesTest {
@BeforeAll
public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemPropertyForKeyVaultJca(PropertyConvertorUtils.SYSTEM_PROPERTIES);
PropertyConvertorUtils.addKeyVaultJcaProvider();
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} |
How about writing these lines into a method in PropertyConvertorUtils? | public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
} | Security.addProvider(provider); | public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemPropertyForKeyVaultJca(PropertyConvertorUtils.SYSTEM_PROPERTIES);
PropertyConvertorUtils.addKeyVaultJcaProvider();
} | class FileSystemCertificatesTest {
private static String certificateName;
@BeforeAll
public static String getFilePath() {
String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} | class FileSystemCertificatesTest {
@BeforeAll
public static String getFilePath() {
String filepath = "\\src\\test\\resources\\custom\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} |
Can we use `allAliases` here? | public boolean engineIsCertificateEntry(String alias) {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.anyMatch(a -> Objects.equals(a, alias));
} | .map(AzureCertificates::getAliases) | public boolean engineIsCertificateEntry(String alias) {
return getAllAliases().contains(alias);
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores all aliases
*/
private final List<String> allAliases = new ArrayList<>();
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = new FileSystemCertificates(wellKnowPath);
customCertificates = new FileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient, this);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
}
@Override
public Enumeration<String> engineAliases() {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
return Collections.enumeration(aliasList);
}
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineDeleteEntry(String alias) {
allCertificates.stream().forEach(a -> a.deleteEntry(alias));
}
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
loadAlias(false);
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
loadAlias(false);
}
void loadAlias(boolean loadKeyVault) {
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
if (loadKeyVault) {
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
}
aliasLists.put("class path certificates", classpathCertificates.getAliases());
loadAllAliases(aliasLists);
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private void loadAllAliases(Map<String, List<String>> aliasLists) {
allAliases.clear();
allAliases.addAll(jreCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias {} under {} already exists", new Object[]{key, a}));
} else {
allAliases.add(a);
}
});
});
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (allAliases.contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList())
.size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getWellKnownFileSystemCertificates(wellKnowPath);
customCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getCustomFileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
}
@Override
public Enumeration<String> engineAliases() {
return Collections.enumeration(getAllAliases());
}
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineDeleteEntry(String alias) {
allCertificates.forEach(a -> a.deleteEntry(alias));
}
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = getAllAliases();
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private List<String> getAllAliases() {
List<String> allAliases = new ArrayList<>();
allAliases.addAll(jreCertificates.getAliases());
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
aliasLists.put("class path certificates", classpathCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias %s under %s already exists", a, key));
} else {
allAliases.add(a);
}
});
});
return allAliases;
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (getAllAliases().contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return getAllAliases().size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} |
Can we use `allAliases` here? | public Enumeration<String> engineAliases() {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
return Collections.enumeration(aliasList);
} | .map(AzureCertificates::getAliases) | public Enumeration<String> engineAliases() {
return Collections.enumeration(getAllAliases());
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores all aliases
*/
private final List<String> allAliases = new ArrayList<>();
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = new FileSystemCertificates(wellKnowPath);
customCertificates = new FileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient, this);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
}
@Override
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineDeleteEntry(String alias) {
allCertificates.stream().forEach(a -> a.deleteEntry(alias));
}
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.anyMatch(a -> Objects.equals(a, alias));
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
loadAlias(false);
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
loadAlias(false);
}
void loadAlias(boolean loadKeyVault) {
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
if (loadKeyVault) {
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
}
aliasLists.put("class path certificates", classpathCertificates.getAliases());
loadAllAliases(aliasLists);
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private void loadAllAliases(Map<String, List<String>> aliasLists) {
allAliases.clear();
allAliases.addAll(jreCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias {} under {} already exists", new Object[]{key, a}));
} else {
allAliases.add(a);
}
});
});
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (allAliases.contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList())
.size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getWellKnownFileSystemCertificates(wellKnowPath);
customCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getCustomFileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
}
@Override
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineDeleteEntry(String alias) {
allCertificates.forEach(a -> a.deleteEntry(alias));
}
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = getAllAliases();
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return getAllAliases().contains(alias);
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private List<String> getAllAliases() {
List<String> allAliases = new ArrayList<>();
allAliases.addAll(jreCertificates.getAliases());
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
aliasLists.put("class path certificates", classpathCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias %s under %s already exists", a, key));
} else {
allAliases.add(a);
}
});
});
return allAliases;
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (getAllAliases().contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return getAllAliases().size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} |
allCertificates.forEach(a -> a.deleteEntry(alias)); | public void engineDeleteEntry(String alias) {
allCertificates.stream().forEach(a -> a.deleteEntry(alias));
} | allCertificates.stream().forEach(a -> a.deleteEntry(alias)); | public void engineDeleteEntry(String alias) {
allCertificates.forEach(a -> a.deleteEntry(alias));
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores all aliases
*/
private final List<String> allAliases = new ArrayList<>();
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = new FileSystemCertificates(wellKnowPath);
customCertificates = new FileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient, this);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
}
@Override
public Enumeration<String> engineAliases() {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
return Collections.enumeration(aliasList);
}
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.anyMatch(a -> Objects.equals(a, alias));
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
loadAlias(false);
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
loadAlias(false);
}
void loadAlias(boolean loadKeyVault) {
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
if (loadKeyVault) {
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
}
aliasLists.put("class path certificates", classpathCertificates.getAliases());
loadAllAliases(aliasLists);
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private void loadAllAliases(Map<String, List<String>> aliasLists) {
allAliases.clear();
allAliases.addAll(jreCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias {} under {} already exists", new Object[]{key, a}));
} else {
allAliases.add(a);
}
});
});
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (allAliases.contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList())
.size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getWellKnownFileSystemCertificates(wellKnowPath);
customCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getCustomFileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
}
@Override
public Enumeration<String> engineAliases() {
return Collections.enumeration(getAllAliases());
}
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = getAllAliases();
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return getAllAliases().contains(alias);
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private List<String> getAllAliases() {
List<String> allAliases = new ArrayList<>();
allAliases.addAll(jreCertificates.getAliases());
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
aliasLists.put("class path certificates", classpathCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias %s under %s already exists", a, key));
} else {
allAliases.add(a);
}
});
});
return allAliases;
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (getAllAliases().contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return getAllAliases().size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} |
Is this path right? | public static String getFilePath() {
String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
} | String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\"; | public static String getFilePath() {
String filepath = "\\src\\test\\resources\\custom\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
} | class FileSystemCertificatesTest {
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} | class FileSystemCertificatesTest {
@BeforeAll
public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemPropertyForKeyVaultJca(PropertyConvertorUtils.SYSTEM_PROPERTIES);
PropertyConvertorUtils.addKeyVaultJcaProvider();
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} |
Could you please add unit test for the priority? For example: 1. wellKnowCertificates and customCertificates has same alias, the first one will be used. 2. Same to customCertificates and classpathCertificates | public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = new FileSystemCertificates(wellKnowPath);
customCertificates = new FileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient, this);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
} | allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates); | public KeyVaultKeyStore() {
creationDate = new Date();
String keyVaultUri = System.getProperty("azure.keyvault.uri");
String tenantId = System.getProperty("azure.keyvault.tenant-id");
String clientId = System.getProperty("azure.keyvault.client-id");
String clientSecret = System.getProperty("azure.keyvault.client-secret");
String managedIdentity = System.getProperty("azure.keyvault.managed-identity");
if (clientId != null) {
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
} else {
keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity);
}
long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval"))
.map(Long::valueOf)
.orElse(0L);
refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate"))
.map(Boolean::parseBoolean)
.orElse(false);
jreCertificates = JreCertificates.getInstance();
wellKnowCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getWellKnownFileSystemCertificates(wellKnowPath);
customCertificates = FileSystemCertificates.FileSystemCertificatesFactory.getCustomFileSystemCertificates(customPath);
keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient);
classpathCertificates = new ClasspathCertificates();
allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates);
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores all aliases
*/
private final List<String> allAliases = new ArrayList<>();
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
@Override
public Enumeration<String> engineAliases() {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
return Collections.enumeration(aliasList);
}
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineDeleteEntry(String alias) {
allCertificates.stream().forEach(a -> a.deleteEntry(alias));
}
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.anyMatch(a -> Objects.equals(a, alias));
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
loadAlias(false);
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
loadAlias(false);
}
void loadAlias(boolean loadKeyVault) {
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
if (loadKeyVault) {
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
}
aliasLists.put("class path certificates", classpathCertificates.getAliases());
loadAllAliases(aliasLists);
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private void loadAllAliases(Map<String, List<String>> aliasLists) {
allAliases.clear();
allAliases.addAll(jreCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias {} under {} already exists", new Object[]{key, a}));
} else {
allAliases.add(a);
}
});
});
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (allAliases.contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return allCertificates.stream()
.map(AzureCertificates::getAliases)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList())
.size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} | class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key-store name.
*/
public static final String KEY_STORE_TYPE = "AzureKeyVault";
/**
* Stores the algorithm name.
*/
public static final String ALGORITHM_NAME = KEY_STORE_TYPE;
/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName());
/**
* Stores the Jre key store certificates.
*/
private final JreCertificates jreCertificates;
/**
* Store well Know certificates loaded from file system.
*/
private final FileSystemCertificates wellKnowCertificates;
/**
* Store custom certificates loaded from file system.
*/
private final FileSystemCertificates customCertificates;
/**
* Store certificates loaded from KeyVault.
*/
private final KeyVaultCertificates keyVaultCertificates;
/**
* Store certificates loaded from classpath.
*/
private final ClasspathCertificates classpathCertificates;
/**
* Stores all the certificates.
*/
private final List<AzureCertificates> allCertificates;
/**
* Stores the creation date.
*/
private final Date creationDate;
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVaultClient;
private final boolean refreshCertificatesWhenHaveUnTrustCertificate;
/**
* Store the path where the well know certificate is placed
*/
final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known"))
.orElse("/etc/certs/well-known/");
/**
* Store the path where the custom certificate is placed
*/
final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom"))
.orElse("/etc/certs/custom/");
/**
* Constructor.
*
* <p>
* The constructor uses System.getProperty for
* <code>azure.keyvault.uri</code>,
* <code>azure.keyvault.aadAuthenticationUrl</code>,
* <code>azure.keyvault.tenantId</code>,
* <code>azure.keyvault.clientId</code>,
* <code>azure.keyvault.clientSecret</code> and
* <code>azure.keyvault.managedIdentity</code> to initialize the
* Key Vault client.
* </p>
*/
@Override
public Enumeration<String> engineAliases() {
return Collections.enumeration(getAllAliases());
}
@Override
public boolean engineContainsAlias(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineDeleteEntry(String alias) {
allCertificates.forEach(a -> a.deleteEntry(alias));
}
@Override
public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) {
return super.engineEntryInstanceOf(alias, entryClass);
}
@Override
public Certificate engineGetCertificate(String alias) {
Certificate certificate = allCertificates.stream()
.map(AzureCertificates::getCertificates)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificates -> certificates.get(alias))
.orElse(null);
if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) {
KeyVaultCertificates.updateLastForceRefreshTime();
certificate = keyVaultCertificates.getCertificates().get(alias);
}
return certificate;
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
List<String> aliasList = getAllAliases();
for (String candidateAlias : aliasList) {
Certificate certificate = engineGetCertificate(candidateAlias);
if (certificate.equals(cert)) {
alias = candidateAlias;
break;
}
}
}
if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) {
alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert);
}
return alias;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
Certificate[] chain = null;
Certificate certificate = engineGetCertificate(alias);
if (certificate != null) {
chain = new Certificate[1];
chain[0] = certificate;
}
return chain;
}
@Override
public Date engineGetCreationDate(String alias) {
return new Date(creationDate.getTime());
}
@Override
public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
return super.engineGetEntry(alias, protParam);
}
@Override
public Key engineGetKey(String alias, char[] password) {
return allCertificates.stream()
.map(AzureCertificates::getCertificateKeys)
.filter(a -> a.containsKey(alias))
.findFirst()
.map(certificateKeys -> certificateKeys.get(alias))
.orElse(null);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return getAllAliases().contains(alias);
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineIsCertificateEntry(alias);
}
@Override
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
if (parameter.getClientId() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
} else if (parameter.getManagedIdentity() != null) {
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getManagedIdentity()
);
} else {
keyVaultClient = new KeyVaultClient(parameter.getUri());
}
keyVaultCertificates.setKeyVaultClient(keyVaultClient);
}
loadCertificates();
}
@Override
public void engineLoad(InputStream stream, char[] password) {
loadCertificates();
}
private void loadCertificates() {
wellKnowCertificates.loadCertificatesFromFileSystem();
customCertificates.loadCertificatesFromFileSystem();
classpathCertificates.loadCertificatesFromClasspath();
}
private List<String> getAllAliases() {
List<String> allAliases = new ArrayList<>();
allAliases.addAll(jreCertificates.getAliases());
Map<String, List<String>> aliasLists = new HashMap<>();
aliasLists.put("well known certificates", wellKnowCertificates.getAliases());
aliasLists.put("custom certificates", customCertificates.getAliases());
aliasLists.put("key vault certificates", keyVaultCertificates.getAliases());
aliasLists.put("class path certificates", classpathCertificates.getAliases());
aliasLists.forEach((key, value) -> {
value.forEach(a -> {
if (allAliases.contains(a)) {
LOGGER.log(WARNING, String.format("The certificate with alias %s under %s already exists", a, key));
} else {
allAliases.add(a);
}
});
});
return allAliases;
}
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (getAllAliases().contains(alias)) {
LOGGER.log(WARNING, "Cannot overwrite own certificate");
return;
}
classpathCertificates.setCertificateEntry(alias, certificate);
}
@Override
public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException {
super.engineSetEntry(alias, entry, protParam);
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) {
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) {
}
@Override
public int engineSize() {
return getAllAliases().size();
}
@Override
public void engineStore(OutputStream stream, char[] password) {
}
@Override
public void engineStore(KeyStore.LoadStoreParameter param) {
}
} |
Could you please click `Resolve conversation` after you finish my suggestion in comments? | public static String getFilePath() {
String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
} | String filepath = "\\src\\test\\java\\com\\azure\\security\\keyvault\\jca\\certificate\\"; | public static String getFilePath() {
String filepath = "\\src\\test\\resources\\custom\\";
return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator"));
} | class FileSystemCertificatesTest {
private static String certificateName;
@BeforeAll
public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemProperty(
Arrays.asList("AZURE_KEYVAULT_URI",
"AZURE_KEYVAULT_TENANT_ID",
"AZURE_KEYVAULT_CLIENT_ID",
"AZURE_KEYVAULT_CLIENT_SECRET")
);
KeyVaultJcaProvider provider = new KeyVaultJcaProvider();
Security.addProvider(provider);
certificateName = System.getenv("AZURE_KEYVAULT_CERTIFICATE_NAME");
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} | class FileSystemCertificatesTest {
@BeforeAll
public static void setEnvironmentProperty() {
System.setProperty("azure.cert-path.custom", getFilePath());
PropertyConvertorUtils.putEnvironmentPropertyToSystemPropertyForKeyVaultJca(PropertyConvertorUtils.SYSTEM_PROPERTIES);
PropertyConvertorUtils.addKeyVaultJcaProvider();
}
@Test
public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore();
Assertions.assertNotNull(keyStore.getCertificate("sideload"));
}
} |
In azure-core-management, only use a simple static `scopes`. | protected String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
return scopes;
} | } | protected String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
return scopes;
} | class ArmChallengeAuthenticationPolicy extends BearerTokenAuthenticationPolicy {
private static final Pattern AUTHENTICATION_CHALLENGE_PATTERN =
Pattern.compile("(\\w+) ((?:\\w+=\".*?\"(?:, )?)+)(?:, )?");
private static final Pattern AUTHENTICATION_CHALLENGE_PARAMS_PATTERN =
Pattern.compile("(?:(\\w+)=\"([^\"\"]*)\")+");
private static final String CLAIMS_PARAMETER = "claims";
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String ARM_SCOPES_KEY = "ARMScopes";
private final String[] scopes;
/**
* Creates ArmChallengeAuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param scopes the scopes used in credential, using default scopes when empty
*/
public ArmChallengeAuthenticationPolicy(TokenCredential credential, String... scopes) {
super(credential, scopes);
this.scopes = scopes;
}
@Override
public Mono<Void> authorizeRequest(HttpPipelineCallContext context) {
return Mono.defer(() -> {
String[] scopes = this.scopes;
scopes = getScopes(context, scopes);
if (scopes == null) {
return Mono.empty();
} else {
context.setData(ARM_SCOPES_KEY, scopes);
return setAuthorizationHeader(context, new TokenRequestContext().addScopes(scopes));
}
});
}
@Override
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) {
return Mono.defer(() -> {
String authHeader = response.getHeaderValue(WWW_AUTHENTICATE);
if (!(response.getStatusCode() == 401 && authHeader != null)) {
return Mono.just(false);
} else {
List<AuthenticationChallenge> challenges = parseChallenges(authHeader);
for (AuthenticationChallenge authenticationChallenge : challenges) {
Map<String, String> extractedChallengeParams =
parseChallengeParams(authenticationChallenge.getChallengeParameters());
if (extractedChallengeParams.containsKey(CLAIMS_PARAMETER)) {
String claims = new String(Base64.getUrlDecoder()
.decode(extractedChallengeParams.get(CLAIMS_PARAMETER)), StandardCharsets.UTF_8);
String[] scopes;
try {
scopes = (String[]) context.getData(ARM_SCOPES_KEY).get();
} catch (NoSuchElementException e) {
scopes = this.scopes;
}
scopes = getScopes(context, scopes);
return setAuthorizationHeader(context, new TokenRequestContext()
.addScopes(scopes).setClaims(claims))
.flatMap(b -> Mono.just(true));
}
}
return Mono.just(false);
}
});
}
List<AuthenticationChallenge> parseChallenges(String header) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PATTERN.matcher(header);
List<AuthenticationChallenge> challenges = new ArrayList<>();
while (matcher.find()) {
challenges.add(new AuthenticationChallenge(matcher.group(1), matcher.group(2)));
}
return challenges;
}
Map<String, String> parseChallengeParams(String challengeParams) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PARAMS_PATTERN.matcher(challengeParams);
Map<String, String> challengeParameters = new HashMap<>();
while (matcher.find()) {
challengeParameters.put(matcher.group(1), matcher.group(2));
}
return challengeParameters;
}
} | class ArmChallengeAuthenticationPolicy extends BearerTokenAuthenticationPolicy {
private static final Pattern AUTHENTICATION_CHALLENGE_PATTERN =
Pattern.compile("(\\w+) ((?:\\w+=\".*?\"(?:, )?)+)(?:, )?");
private static final Pattern AUTHENTICATION_CHALLENGE_PARAMS_PATTERN =
Pattern.compile("(?:(\\w+)=\"([^\"\"]*)\")+");
private static final String CLAIMS_PARAMETER = "claims";
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String ARM_SCOPES_KEY = "ARMScopes";
private final String[] scopes;
/**
* Creates ArmChallengeAuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param scopes the scopes used in credential, using default scopes when empty
*/
public ArmChallengeAuthenticationPolicy(TokenCredential credential, String... scopes) {
super(credential, scopes);
this.scopes = scopes;
}
@Override
public Mono<Void> authorizeRequest(HttpPipelineCallContext context) {
return Mono.defer(() -> {
String[] scopes = this.scopes;
scopes = getScopes(context, scopes);
if (scopes == null) {
return Mono.empty();
} else {
context.setData(ARM_SCOPES_KEY, scopes);
return setAuthorizationHeader(context, new TokenRequestContext().addScopes(scopes));
}
});
}
@Override
public Mono<Boolean> authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) {
return Mono.defer(() -> {
String authHeader = response.getHeaderValue(WWW_AUTHENTICATE);
if (!(response.getStatusCode() == 401 && authHeader != null)) {
return Mono.just(false);
} else {
List<AuthenticationChallenge> challenges = parseChallenges(authHeader);
for (AuthenticationChallenge authenticationChallenge : challenges) {
Map<String, String> extractedChallengeParams =
parseChallengeParams(authenticationChallenge.getChallengeParameters());
if (extractedChallengeParams.containsKey(CLAIMS_PARAMETER)) {
String claims = new String(Base64.getUrlDecoder()
.decode(extractedChallengeParams.get(CLAIMS_PARAMETER)), StandardCharsets.UTF_8);
String[] scopes;
try {
scopes = (String[]) context.getData(ARM_SCOPES_KEY).get();
} catch (NoSuchElementException e) {
scopes = this.scopes;
}
scopes = getScopes(context, scopes);
return setAuthorizationHeader(context, new TokenRequestContext()
.addScopes(scopes).setClaims(claims))
.flatMap(b -> Mono.just(true));
}
}
return Mono.just(false);
}
});
}
List<AuthenticationChallenge> parseChallenges(String header) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PATTERN.matcher(header);
List<AuthenticationChallenge> challenges = new ArrayList<>();
while (matcher.find()) {
challenges.add(new AuthenticationChallenge(matcher.group(1), matcher.group(2)));
}
return challenges;
}
Map<String, String> parseChallengeParams(String challengeParams) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PARAMS_PATTERN.matcher(challengeParams);
Map<String, String> challengeParameters = new HashMap<>();
while (matcher.find()) {
challengeParameters.put(matcher.group(1), matcher.group(2));
}
return challengeParameters;
}
} |
Dynamic `scopes` in azure-resourcemanager-resources. It depends on `AccessTokenCache` to retrieve new token when scopes changed. | protected String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
if (CoreUtils.isNullOrEmpty(scopes)) {
scopes = new String[1];
scopes[0] = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment);
}
return scopes;
} | scopes[0] = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment); | protected String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
if (CoreUtils.isNullOrEmpty(scopes)) {
scopes = new String[1];
scopes[0] = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment);
}
return scopes;
} | class AuthenticationPolicy extends ArmChallengeAuthenticationPolicy {
private final AzureEnvironment environment;
/**
* Creates AuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param environment the environment with endpoints for authentication
* @param scopes the scopes used in credential, using default scopes when empty
*/
public AuthenticationPolicy(TokenCredential credential, AzureEnvironment environment, String... scopes) {
super(credential, scopes);
this.environment = environment;
}
@Override
} | class AuthenticationPolicy extends ArmChallengeAuthenticationPolicy {
private final AzureEnvironment environment;
/**
* Creates AuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param environment the environment with endpoints for authentication
* @param scopes the scopes used in credential, using default scopes when empty
*/
public AuthenticationPolicy(TokenCredential credential, AzureEnvironment environment, String... scopes) {
super(credential, scopes);
this.environment = environment;
}
@Override
} |
Yeah the AccessTokenCache will retreive a new token if a different scope is passed in. | protected String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
if (CoreUtils.isNullOrEmpty(scopes)) {
scopes = new String[1];
scopes[0] = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment);
}
return scopes;
} | scopes[0] = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment); | protected String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
if (CoreUtils.isNullOrEmpty(scopes)) {
scopes = new String[1];
scopes[0] = ResourceManagerUtils.getDefaultScopeFromRequest(context.getHttpRequest(), environment);
}
return scopes;
} | class AuthenticationPolicy extends ArmChallengeAuthenticationPolicy {
private final AzureEnvironment environment;
/**
* Creates AuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param environment the environment with endpoints for authentication
* @param scopes the scopes used in credential, using default scopes when empty
*/
public AuthenticationPolicy(TokenCredential credential, AzureEnvironment environment, String... scopes) {
super(credential, scopes);
this.environment = environment;
}
@Override
} | class AuthenticationPolicy extends ArmChallengeAuthenticationPolicy {
private final AzureEnvironment environment;
/**
* Creates AuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param environment the environment with endpoints for authentication
* @param scopes the scopes used in credential, using default scopes when empty
*/
public AuthenticationPolicy(TokenCredential credential, AzureEnvironment environment, String... scopes) {
super(credential, scopes);
this.environment = environment;
}
@Override
} |
return new PlayAudioRequestInternal() .setOperationContext(request.getOperationContext()) .setAudioFileUri(request.getAudioFileUri()) .setAudioFileId(request.getAudioFileId()) .setLoop(request.isLoop()); | private PlayAudioRequestInternal convertPlayAudioRequest(PlayAudioRequest request) {
PlayAudioRequestInternal playAudioRequestInternal = new PlayAudioRequestInternal();
playAudioRequestInternal.setAudioFileUri(request.getAudioFileUri());
playAudioRequestInternal.setAudioFileId(request.getAudioFileId());
playAudioRequestInternal.setLoop(request.isLoop());
playAudioRequestInternal.setOperationContext(request.getOperationContext());
return playAudioRequestInternal;
} | PlayAudioRequestInternal playAudioRequestInternal = new PlayAudioRequestInternal(); | private PlayAudioRequestInternal convertPlayAudioRequest(PlayAudioRequest request) {
PlayAudioRequestInternal playAudioRequestInternal = new PlayAudioRequestInternal();
playAudioRequestInternal.setAudioFileUri(request.getAudioFileUri());
playAudioRequestInternal.setAudioFileId(request.getAudioFileId());
playAudioRequestInternal.setLoop(request.isLoop());
playAudioRequestInternal.setOperationContext(request.getOperationContext());
return playAudioRequestInternal;
} | class CallAsyncClient {
private final CallsImpl callClient;
private final ClientLogger logger = new ClientLogger(CallAsyncClient.class);
CallAsyncClient(AzureCommunicationCallingServerServiceImpl callServiceClient) {
callClient = callServiceClient.getCalls();
}
/**
* Create a Call Request from source identity to targets identity.
*
* @param source The source of the call.
* @param targets The targets of the call.
* @param createCallOptions The call Options.
* @return response for a successful CreateCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<CreateCallResult> createCall(CommunicationIdentifier source, Iterable<CommunicationIdentifier> targets,
CreateCallOptions createCallOptions) {
try {
Objects.requireNonNull(source, "'source' cannot be null.");
Objects.requireNonNull(targets, "'targets' cannot be null.");
Objects.requireNonNull(createCallOptions, "'CreateCallOptions' cannot be null.");
CreateCallRequestInternal request = createCreateCallRequest(source, targets, createCallOptions);
return this.callClient.createCallAsync(request).flatMap((CreateCallResponse response) -> {
CreateCallResult createCallResult = convertCreateCallWithResponse(response);
return Mono.just(createCallResult);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Create a Call Request from source identity to targets identity.
*
* @param source The source of the call.
* @param targets The targets of the call.
* @param createCallOptions The call Options.
* @return response for a successful CreateCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<CreateCallResult>> createCallWithResponse(CommunicationIdentifier source,
Iterable<CommunicationIdentifier> targets, CreateCallOptions createCallOptions) {
return createCallWithResponse(source, targets, createCallOptions, null);
}
Mono<Response<CreateCallResult>> createCallWithResponse(CommunicationIdentifier source,
Iterable<CommunicationIdentifier> targets, CreateCallOptions createCallOptions, Context context) {
try {
Objects.requireNonNull(source, "'source' cannot be null.");
Objects.requireNonNull(targets, "'targets' cannot be null.");
Objects.requireNonNull(createCallOptions, "'CreateCallOptions' cannot be null.");
CreateCallRequestInternal request = createCreateCallRequest(source, targets, createCallOptions);
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.createCallWithResponseAsync(request)
.flatMap((Response<CreateCallResponse> response) -> {
CreateCallResult createCallResult = convertCreateCallWithResponse(response.getValue());
return Mono.just(new SimpleResponse<>(response, createCallResult));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Play audio in a call.
*
* @param callId The call id.
* @param request Play audio request.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PlayAudioResult> playAudio(String callId, PlayAudioRequest request) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return this.callClient.playAudioAsync(callId, convertPlayAudioRequest(request)).flatMap(
(com.azure.communication.callingserver.implementation.models.PlayAudioResponse response) -> {
PlayAudioResult playAudioResult = convertPlayAudioResponse(response);
return Mono.just(playAudioResult);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Play audio in a call.
*
* @param callId The call id.
* @param request Play audio request.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<PlayAudioResult>> playAudioWithResponse(String callId, PlayAudioRequest request) {
return playAudioWithResponse(callId, request, null);
}
Mono<Response<PlayAudioResult>> playAudioWithResponse(String callId, PlayAudioRequest request, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.playAudioWithResponseAsync(callId, convertPlayAudioRequest(request)).flatMap((
Response<com.azure.communication.callingserver.implementation.models.PlayAudioResponse> response) -> {
PlayAudioResult playAudioResult = convertPlayAudioResponse(response.getValue());
return Mono.just(new SimpleResponse<>(response, playAudioResult));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Hangup a call.
*
* @param callId Call id.
* @return response for a successful HangupCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> hangupCall(String callId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return this.callClient.hangupCallAsync(callId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Hangup a call.
*
* @param callId Call id.
* @return response for a successful HangupCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> hangupCallWithResponse(String callId) {
return hangupCallWithResponse(callId, null);
}
Mono<Response<Void>> hangupCallWithResponse(String callId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.hangupCallWithResponseAsync(callId);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete a call.
*
* @param callId Call id.
* @return response for a successful DeleteCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteCall(String callId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return this.callClient.deleteCallAsync(callId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete a call.
*
* @param callId Call id.
* @return response for a successful DeleteCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteCallWithResponse(String callId) {
return deleteCallWithResponse(callId, null);
}
Mono<Response<Void>> deleteCallWithResponse(String callId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.deleteCallWithResponseAsync(callId);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId The call leg id.
* @return the response payload of the cancel media operations.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<CancelMediaOperationsResult> cancelMediaOperations(String callId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return this.callClient.cancelMediaOperationsAsync(callId)
.flatMap((
com.azure.communication.callingserver.implementation.models.CancelMediaOperationsResponse response) -> {
CancelMediaOperationsResult cancelMediaOperationsResult = convertCancelMediaOperationsResponse(
response);
return Mono.just(cancelMediaOperationsResult);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId The call leg id.
* @return the response payload of the cancel media operations.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<CancelMediaOperationsResult>> cancelMediaOperationsWithResponse(String callId) {
return cancelMediaOperationsWithResponse(callId, null);
}
Mono<Response<CancelMediaOperationsResult>> cancelMediaOperationsWithResponse(String callId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient
.cancelMediaOperationsWithResponseAsync(callId, context)
.flatMap((
Response<com.azure.communication.callingserver.implementation.models.CancelMediaOperationsResponse> response) -> {
CancelMediaOperationsResult cancelMediaOperationsResult = convertCancelMediaOperationsResponse(
response.getValue());
return Mono.just(new SimpleResponse<>(response, cancelMediaOperationsResult));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId Call id.
* @param request Invite participant request.
* @return response for a successful inviteParticipants request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> inviteParticipants(String callId, InviteParticipantsRequest request) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return this.callClient.inviteParticipantsAsync(callId, InviteParticipantsRequestConverter.convert(request));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId Call id.
* @param request Invite participant request.
* @return response for a successful inviteParticipants request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> inviteParticipantsWithResponse(String callId, InviteParticipantsRequest request) {
return inviteParticipantsWithResponse(callId, request, null);
}
Mono<Response<Void>> inviteParticipantsWithResponse(String callId, InviteParticipantsRequest request, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.inviteParticipantsWithResponseAsync(callId,
InviteParticipantsRequestConverter.convert(request));
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove participant from the call.
*
* @param callId Call id.
* @param participantId Participant id.
* @return response for a successful removeParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> removeParticipant(String callId, String participantId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(participantId, "'request' cannot be null.");
return this.callClient.removeParticipantAsync(callId, participantId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove participant from the call.
*
* @param callId Call id.
* @param participantId Participant id.
* @return response for a successful removeParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> removeParticipantWithResponse(String callId, String participantId) {
return removeParticipantWithResponse(callId, participantId, null);
}
/**
* cancelMediaOperationsWithResponse method for use by sync client
*/
Mono<Response<Void>> removeParticipantWithResponse(String callId, String participantId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(participantId, "'request' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.removeParticipantWithResponseAsync(callId, participantId);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private CreateCallRequestInternal createCreateCallRequest(CommunicationIdentifier source,
Iterable<CommunicationIdentifier> targets, CreateCallOptions createCallOptions) {
CreateCallRequestInternal request = new CreateCallRequestInternal();
List<CommunicationIdentifier> targetsList = new ArrayList<>();
targets.forEach(targetsList::add);
List<CallModalityModel> requestedModalities = new ArrayList<>();
for (CallModality modality : createCallOptions.getRequestedModalities()) {
requestedModalities.add(CallModalityModel.fromString(modality.toString()));
}
List<EventSubscriptionTypeModel> requestedCallEvents = new ArrayList<>();
for (EventSubscriptionType requestedCallEvent : createCallOptions.getRequestedCallEvents()) {
requestedCallEvents.add(EventSubscriptionTypeModel.fromString(requestedCallEvent.toString()));
}
PhoneNumberIdentifierModel sourceAlternateIdentity = createCallOptions.getAlternateCallerId() == null
? null : new PhoneNumberIdentifierModel().setValue(createCallOptions.getAlternateCallerId().getPhoneNumber());
request.setSource(CommunicationIdentifierConverter.convert(source))
.setTargets(targetsList.stream().map(target -> CommunicationIdentifierConverter.convert(target))
.collect(Collectors.toList()))
.setCallbackUri(createCallOptions.getCallbackUri()).setRequestedModalities(requestedModalities)
.setRequestedCallEvents(requestedCallEvents).setSourceAlternateIdentity(sourceAlternateIdentity);
return request;
}
private PlayAudioResult convertPlayAudioResponse(
com.azure.communication.callingserver.implementation.models.PlayAudioResponse response) {
return new PlayAudioResult().setId(response.getId())
.setStatus(OperationStatus.fromString(response.getStatus().toString()))
.setOperationContext(response.getOperationContext())
.setResultInfo(ResultInfoConverter.convert(response.getResultInfo()));
}
private CancelMediaOperationsResult convertCancelMediaOperationsResponse(
com.azure.communication.callingserver.implementation.models.CancelMediaOperationsResponse response) {
return new CancelMediaOperationsResult().setId(response.getId())
.setStatus(OperationStatus.fromString(response.getStatus().toString()))
.setOperationContext(response.getOperationContext())
.setResultInfo(ResultInfoConverter.convert(response.getResultInfo()));
}
private CreateCallResult convertCreateCallWithResponse(CreateCallResponse response) {
return new CreateCallResult().setCallLegId(response.getCallLegId());
}
} | class CallAsyncClient {
private final CallsImpl callClient;
private final ClientLogger logger = new ClientLogger(CallAsyncClient.class);
CallAsyncClient(AzureCommunicationCallingServerServiceImpl callServiceClient) {
callClient = callServiceClient.getCalls();
}
/**
* Create a Call Request from source identity to targets identity.
*
* @param source The source of the call.
* @param targets The targets of the call.
* @param createCallOptions The call Options.
* @return response for a successful CreateCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<CreateCallResult> createCall(CommunicationIdentifier source, Iterable<CommunicationIdentifier> targets,
CreateCallOptions createCallOptions) {
try {
Objects.requireNonNull(source, "'source' cannot be null.");
Objects.requireNonNull(targets, "'targets' cannot be null.");
Objects.requireNonNull(createCallOptions, "'CreateCallOptions' cannot be null.");
CreateCallRequestInternal request = createCreateCallRequest(source, targets, createCallOptions);
return this.callClient.createCallAsync(request).flatMap((CreateCallResponse response) -> {
CreateCallResult createCallResult = convertCreateCallWithResponse(response);
return Mono.just(createCallResult);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Create a Call Request from source identity to targets identity.
*
* @param source The source of the call.
* @param targets The targets of the call.
* @param createCallOptions The call Options.
* @return response for a successful CreateCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<CreateCallResult>> createCallWithResponse(CommunicationIdentifier source,
Iterable<CommunicationIdentifier> targets, CreateCallOptions createCallOptions) {
return createCallWithResponse(source, targets, createCallOptions, null);
}
Mono<Response<CreateCallResult>> createCallWithResponse(CommunicationIdentifier source,
Iterable<CommunicationIdentifier> targets, CreateCallOptions createCallOptions, Context context) {
try {
Objects.requireNonNull(source, "'source' cannot be null.");
Objects.requireNonNull(targets, "'targets' cannot be null.");
Objects.requireNonNull(createCallOptions, "'CreateCallOptions' cannot be null.");
CreateCallRequestInternal request = createCreateCallRequest(source, targets, createCallOptions);
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.createCallWithResponseAsync(request)
.flatMap((Response<CreateCallResponse> response) -> {
CreateCallResult createCallResult = convertCreateCallWithResponse(response.getValue());
return Mono.just(new SimpleResponse<>(response, createCallResult));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Play audio in a call.
*
* @param callId The call id.
* @param request Play audio request.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PlayAudioResult> playAudio(String callId, PlayAudioRequest request) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return this.callClient.playAudioAsync(callId, convertPlayAudioRequest(request)).flatMap(
(com.azure.communication.callingserver.implementation.models.PlayAudioResponse response) -> {
PlayAudioResult playAudioResult = convertPlayAudioResponse(response);
return Mono.just(playAudioResult);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Play audio in a call.
*
* @param callId The call id.
* @param request Play audio request.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<PlayAudioResult>> playAudioWithResponse(String callId, PlayAudioRequest request) {
return playAudioWithResponse(callId, request, null);
}
Mono<Response<PlayAudioResult>> playAudioWithResponse(String callId, PlayAudioRequest request, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.playAudioWithResponseAsync(callId, convertPlayAudioRequest(request)).flatMap((
Response<com.azure.communication.callingserver.implementation.models.PlayAudioResponse> response) -> {
PlayAudioResult playAudioResult = convertPlayAudioResponse(response.getValue());
return Mono.just(new SimpleResponse<>(response, playAudioResult));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Hangup a call.
*
* @param callId Call id.
* @return response for a successful HangupCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> hangupCall(String callId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return this.callClient.hangupCallAsync(callId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Hangup a call.
*
* @param callId Call id.
* @return response for a successful HangupCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> hangupCallWithResponse(String callId) {
return hangupCallWithResponse(callId, null);
}
Mono<Response<Void>> hangupCallWithResponse(String callId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.hangupCallWithResponseAsync(callId);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete a call.
*
* @param callId Call id.
* @return response for a successful DeleteCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteCall(String callId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return this.callClient.deleteCallAsync(callId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Delete a call.
*
* @param callId Call id.
* @return response for a successful DeleteCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteCallWithResponse(String callId) {
return deleteCallWithResponse(callId, null);
}
Mono<Response<Void>> deleteCallWithResponse(String callId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.deleteCallWithResponseAsync(callId);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId The call leg id.
* @return the response payload of the cancel media operations.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<CancelMediaOperationsResult> cancelMediaOperations(String callId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return this.callClient.cancelMediaOperationsAsync(callId)
.flatMap((
com.azure.communication.callingserver.implementation.models.CancelMediaOperationsResponse response) -> {
CancelMediaOperationsResult cancelMediaOperationsResult = convertCancelMediaOperationsResponse(
response);
return Mono.just(cancelMediaOperationsResult);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId The call leg id.
* @return the response payload of the cancel media operations.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<CancelMediaOperationsResult>> cancelMediaOperationsWithResponse(String callId) {
return cancelMediaOperationsWithResponse(callId, null);
}
Mono<Response<CancelMediaOperationsResult>> cancelMediaOperationsWithResponse(String callId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient
.cancelMediaOperationsWithResponseAsync(callId, context)
.flatMap((
Response<com.azure.communication.callingserver.implementation.models.CancelMediaOperationsResponse> response) -> {
CancelMediaOperationsResult cancelMediaOperationsResult = convertCancelMediaOperationsResponse(
response.getValue());
return Mono.just(new SimpleResponse<>(response, cancelMediaOperationsResult));
});
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId Call id.
* @param request Invite participant request.
* @return response for a successful inviteParticipants request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> inviteParticipants(String callId, InviteParticipantsRequest request) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return this.callClient.inviteParticipantsAsync(callId, InviteParticipantsRequestConverter.convert(request));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Cancel Media Operations.
*
* @param callId Call id.
* @param request Invite participant request.
* @return response for a successful inviteParticipants request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> inviteParticipantsWithResponse(String callId, InviteParticipantsRequest request) {
return inviteParticipantsWithResponse(callId, request, null);
}
Mono<Response<Void>> inviteParticipantsWithResponse(String callId, InviteParticipantsRequest request, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(request, "'request' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.inviteParticipantsWithResponseAsync(callId,
InviteParticipantsRequestConverter.convert(request));
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove participant from the call.
*
* @param callId Call id.
* @param participantId Participant id.
* @return response for a successful removeParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> removeParticipant(String callId, String participantId) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(participantId, "'request' cannot be null.");
return this.callClient.removeParticipantAsync(callId, participantId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove participant from the call.
*
* @param callId Call id.
* @param participantId Participant id.
* @return response for a successful removeParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> removeParticipantWithResponse(String callId, String participantId) {
return removeParticipantWithResponse(callId, participantId, null);
}
/**
* cancelMediaOperationsWithResponse method for use by sync client
*/
Mono<Response<Void>> removeParticipantWithResponse(String callId, String participantId, Context context) {
try {
Objects.requireNonNull(callId, "'callId' cannot be null.");
Objects.requireNonNull(participantId, "'request' cannot be null.");
return withContext(contextValue -> {
if (context != null) {
contextValue = context;
}
return this.callClient.removeParticipantWithResponseAsync(callId, participantId);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private CreateCallRequestInternal createCreateCallRequest(CommunicationIdentifier source,
Iterable<CommunicationIdentifier> targets, CreateCallOptions createCallOptions) {
CreateCallRequestInternal request = new CreateCallRequestInternal();
List<CommunicationIdentifier> targetsList = new ArrayList<>();
targets.forEach(targetsList::add);
List<CallModalityModel> requestedModalities = new ArrayList<>();
for (CallModality modality : createCallOptions.getRequestedModalities()) {
requestedModalities.add(CallModalityModel.fromString(modality.toString()));
}
List<EventSubscriptionTypeModel> requestedCallEvents = new ArrayList<>();
for (EventSubscriptionType requestedCallEvent : createCallOptions.getRequestedCallEvents()) {
requestedCallEvents.add(EventSubscriptionTypeModel.fromString(requestedCallEvent.toString()));
}
PhoneNumberIdentifierModel sourceAlternateIdentity = createCallOptions.getAlternateCallerId() == null
? null : new PhoneNumberIdentifierModel().setValue(createCallOptions.getAlternateCallerId().getPhoneNumber());
request.setSource(CommunicationIdentifierConverter.convert(source))
.setTargets(targetsList.stream().map(target -> CommunicationIdentifierConverter.convert(target))
.collect(Collectors.toList()))
.setCallbackUri(createCallOptions.getCallbackUri()).setRequestedModalities(requestedModalities)
.setRequestedCallEvents(requestedCallEvents).setSourceAlternateIdentity(sourceAlternateIdentity);
return request;
}
private PlayAudioResult convertPlayAudioResponse(
com.azure.communication.callingserver.implementation.models.PlayAudioResponse response) {
return new PlayAudioResult().setId(response.getId())
.setStatus(OperationStatus.fromString(response.getStatus().toString()))
.setOperationContext(response.getOperationContext())
.setResultInfo(ResultInfoConverter.convert(response.getResultInfo()));
}
private CancelMediaOperationsResult convertCancelMediaOperationsResponse(
com.azure.communication.callingserver.implementation.models.CancelMediaOperationsResponse response) {
return new CancelMediaOperationsResult().setId(response.getId())
.setStatus(OperationStatus.fromString(response.getStatus().toString()))
.setOperationContext(response.getOperationContext())
.setResultInfo(ResultInfoConverter.convert(response.getResultInfo()));
}
private CreateCallResult convertCreateCallWithResponse(CreateCallResponse response) {
return new CreateCallResult().setCallLegId(response.getCallLegId());
}
} |
You add a replace scenario. How about append scenario? Should we consider it? | public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String... ids) {
destinationAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
} | } | public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String... ids) {
destinationAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
} | class NetworkSecurityRuleImpl
extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup>
implements NetworkSecurityRule,
NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>,
NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>,
NetworkSecurityRule.Update {
private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>();
private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>();
private final ClientLogger logger = new ClientLogger(getClass());
NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) {
super(inner, parent);
if (inner.sourceApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) {
sourceAsgs.put(asg.id(), asg);
}
}
if (inner.destinationApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) {
destinationAsgs.put(asg.id(), asg);
}
}
}
@Override
public String name() {
return this.innerModel().name();
}
@Override
public SecurityRuleDirection direction() {
return this.innerModel().direction();
}
@Override
public SecurityRuleProtocol protocol() {
return this.innerModel().protocol();
}
@Override
public SecurityRuleAccess access() {
return this.innerModel().access();
}
@Override
public String sourceAddressPrefix() {
return this.innerModel().sourceAddressPrefix();
}
@Override
public List<String> sourceAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().sourceAddressPrefixes());
}
@Override
public String sourcePortRange() {
return this.innerModel().sourcePortRange();
}
@Override
public List<String> sourcePortRanges() {
return Collections.unmodifiableList(innerModel().sourcePortRanges());
}
@Override
public String destinationAddressPrefix() {
return this.innerModel().destinationAddressPrefix();
}
@Override
public List<String> destinationAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().destinationAddressPrefixes());
}
@Override
public String destinationPortRange() {
return this.innerModel().destinationPortRange();
}
@Override
public List<String> destinationPortRanges() {
return Collections.unmodifiableList(innerModel().destinationPortRanges());
}
@Override
public int priority() {
return ResourceManagerUtils.toPrimitiveInt(this.innerModel().priority());
}
@Override
public Set<String> sourceApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(sourceAsgs.keySet());
}
@Override
public Set<String> destinationApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(destinationAsgs.keySet());
}
@Override
public NetworkSecurityRuleImpl allowInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl allowOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl denyInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl denyOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) {
this.innerModel().withProtocol(protocol);
return this;
}
@Override
public NetworkSecurityRuleImpl withAnyProtocol() {
return this.withProtocol(SecurityRuleProtocol.ASTERISK);
}
@Override
public NetworkSecurityRuleImpl fromAddress(String cidr) {
this.innerModel().withSourceAddressPrefix(cidr);
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyAddress() {
this.innerModel().withSourceAddressPrefix("*");
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAddresses(String... addresses) {
this.innerModel().withSourceAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withSourceAddressPrefix(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPort(int port) {
this.innerModel().withSourcePortRange(String.valueOf(port));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyPort() {
this.innerModel().withSourcePortRange("*");
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRange(int from, int to) {
this.innerModel().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRanges(String... ranges) {
this.innerModel().withSourcePortRanges(Arrays.asList(ranges));
this.innerModel().withSourcePortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddress(String cidr) {
this.innerModel().withDestinationAddressPrefix(cidr);
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddresses(String... addresses) {
this.innerModel().withDestinationAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withDestinationAddressPrefix(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyAddress() {
this.innerModel().withDestinationAddressPrefix("*");
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPort(int port) {
this.innerModel().withDestinationPortRange(String.valueOf(port));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyPort() {
this.innerModel().withDestinationPortRange("*");
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRange(int from, int to) {
this.innerModel().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRanges(String... ranges) {
this.innerModel().withDestinationPortRanges(Arrays.asList(ranges));
this.innerModel().withDestinationPortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withPriority(int priority) {
if (priority < 100 || priority > 4096) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"The priority number of a network security rule must be between 100 and 4096."));
}
this.innerModel().withPriority(priority);
return this;
}
@Override
public NetworkSecurityRuleImpl withDescription(String description) {
this.innerModel().withDescription(description);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) {
sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutSourceApplicationSecurityGroup(String id) {
sourceAsgs.remove(id);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String... ids) {
sourceAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) {
destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutDestinationApplicationSecurityGroup(String id) {
destinationAsgs.remove(id);
return this;
}
@Override
private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) {
this.innerModel().withDirection(direction);
return this;
}
private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) {
this.innerModel().withAccess(permission);
return this;
}
@Override
public NetworkSecurityGroupImpl attach() {
return this.parent().withRule(this);
}
@Override
public NetworkSecurityGroupImpl parent() {
innerModel().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values()));
innerModel().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values()));
return super.parent();
}
@Override
public String description() {
return this.innerModel().description();
}
} | class NetworkSecurityRuleImpl
extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup>
implements NetworkSecurityRule,
NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>,
NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>,
NetworkSecurityRule.Update {
private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>();
private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>();
private final ClientLogger logger = new ClientLogger(getClass());
NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) {
super(inner, parent);
if (inner.sourceApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) {
sourceAsgs.put(asg.id(), asg);
}
}
if (inner.destinationApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) {
destinationAsgs.put(asg.id(), asg);
}
}
}
@Override
public String name() {
return this.innerModel().name();
}
@Override
public SecurityRuleDirection direction() {
return this.innerModel().direction();
}
@Override
public SecurityRuleProtocol protocol() {
return this.innerModel().protocol();
}
@Override
public SecurityRuleAccess access() {
return this.innerModel().access();
}
@Override
public String sourceAddressPrefix() {
return this.innerModel().sourceAddressPrefix();
}
@Override
public List<String> sourceAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().sourceAddressPrefixes());
}
@Override
public String sourcePortRange() {
return this.innerModel().sourcePortRange();
}
@Override
public List<String> sourcePortRanges() {
return Collections.unmodifiableList(innerModel().sourcePortRanges());
}
@Override
public String destinationAddressPrefix() {
return this.innerModel().destinationAddressPrefix();
}
@Override
public List<String> destinationAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().destinationAddressPrefixes());
}
@Override
public String destinationPortRange() {
return this.innerModel().destinationPortRange();
}
@Override
public List<String> destinationPortRanges() {
return Collections.unmodifiableList(innerModel().destinationPortRanges());
}
@Override
public int priority() {
return ResourceManagerUtils.toPrimitiveInt(this.innerModel().priority());
}
@Override
public Set<String> sourceApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(sourceAsgs.keySet());
}
@Override
public Set<String> destinationApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(destinationAsgs.keySet());
}
@Override
public NetworkSecurityRuleImpl allowInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl allowOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl denyInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl denyOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) {
this.innerModel().withProtocol(protocol);
return this;
}
@Override
public NetworkSecurityRuleImpl withAnyProtocol() {
return this.withProtocol(SecurityRuleProtocol.ASTERISK);
}
@Override
public NetworkSecurityRuleImpl fromAddress(String cidr) {
this.innerModel().withSourceAddressPrefix(cidr);
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyAddress() {
this.innerModel().withSourceAddressPrefix("*");
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAddresses(String... addresses) {
this.innerModel().withSourceAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withSourceAddressPrefix(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPort(int port) {
this.innerModel().withSourcePortRange(String.valueOf(port));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyPort() {
this.innerModel().withSourcePortRange("*");
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRange(int from, int to) {
this.innerModel().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRanges(String... ranges) {
this.innerModel().withSourcePortRanges(Arrays.asList(ranges));
this.innerModel().withSourcePortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddress(String cidr) {
this.innerModel().withDestinationAddressPrefix(cidr);
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddresses(String... addresses) {
this.innerModel().withDestinationAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withDestinationAddressPrefix(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyAddress() {
this.innerModel().withDestinationAddressPrefix("*");
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPort(int port) {
this.innerModel().withDestinationPortRange(String.valueOf(port));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyPort() {
this.innerModel().withDestinationPortRange("*");
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRange(int from, int to) {
this.innerModel().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRanges(String... ranges) {
this.innerModel().withDestinationPortRanges(Arrays.asList(ranges));
this.innerModel().withDestinationPortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withPriority(int priority) {
if (priority < 100 || priority > 4096) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"The priority number of a network security rule must be between 100 and 4096."));
}
this.innerModel().withPriority(priority);
return this;
}
@Override
public NetworkSecurityRuleImpl withDescription(String description) {
this.innerModel().withDescription(description);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) {
sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutSourceApplicationSecurityGroup(String id) {
sourceAsgs.remove(id);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String... ids) {
sourceAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) {
destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutDestinationApplicationSecurityGroup(String id) {
destinationAsgs.remove(id);
return this;
}
@Override
private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) {
this.innerModel().withDirection(direction);
return this;
}
private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) {
this.innerModel().withAccess(permission);
return this;
}
@Override
public NetworkSecurityGroupImpl attach() {
return this.parent().withRule(this);
}
@Override
public NetworkSecurityGroupImpl parent() {
innerModel().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values()));
innerModel().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values()));
return super.parent();
}
@Override
public String description() {
return this.innerModel().description();
}
} |
In update flow, one can call multiple `withDestinationApplicationSecurityGroup` and `withoutDestinationApplicationSecurityGroup` to update the list (there is no method taking multiple ids in update flow). In create flow, one just choose the method that take 1 id, or multiple ids. No replace or append. | public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String... ids) {
destinationAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
} | } | public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String... ids) {
destinationAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
} | class NetworkSecurityRuleImpl
extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup>
implements NetworkSecurityRule,
NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>,
NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>,
NetworkSecurityRule.Update {
private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>();
private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>();
private final ClientLogger logger = new ClientLogger(getClass());
NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) {
super(inner, parent);
if (inner.sourceApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) {
sourceAsgs.put(asg.id(), asg);
}
}
if (inner.destinationApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) {
destinationAsgs.put(asg.id(), asg);
}
}
}
@Override
public String name() {
return this.innerModel().name();
}
@Override
public SecurityRuleDirection direction() {
return this.innerModel().direction();
}
@Override
public SecurityRuleProtocol protocol() {
return this.innerModel().protocol();
}
@Override
public SecurityRuleAccess access() {
return this.innerModel().access();
}
@Override
public String sourceAddressPrefix() {
return this.innerModel().sourceAddressPrefix();
}
@Override
public List<String> sourceAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().sourceAddressPrefixes());
}
@Override
public String sourcePortRange() {
return this.innerModel().sourcePortRange();
}
@Override
public List<String> sourcePortRanges() {
return Collections.unmodifiableList(innerModel().sourcePortRanges());
}
@Override
public String destinationAddressPrefix() {
return this.innerModel().destinationAddressPrefix();
}
@Override
public List<String> destinationAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().destinationAddressPrefixes());
}
@Override
public String destinationPortRange() {
return this.innerModel().destinationPortRange();
}
@Override
public List<String> destinationPortRanges() {
return Collections.unmodifiableList(innerModel().destinationPortRanges());
}
@Override
public int priority() {
return ResourceManagerUtils.toPrimitiveInt(this.innerModel().priority());
}
@Override
public Set<String> sourceApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(sourceAsgs.keySet());
}
@Override
public Set<String> destinationApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(destinationAsgs.keySet());
}
@Override
public NetworkSecurityRuleImpl allowInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl allowOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl denyInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl denyOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) {
this.innerModel().withProtocol(protocol);
return this;
}
@Override
public NetworkSecurityRuleImpl withAnyProtocol() {
return this.withProtocol(SecurityRuleProtocol.ASTERISK);
}
@Override
public NetworkSecurityRuleImpl fromAddress(String cidr) {
this.innerModel().withSourceAddressPrefix(cidr);
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyAddress() {
this.innerModel().withSourceAddressPrefix("*");
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAddresses(String... addresses) {
this.innerModel().withSourceAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withSourceAddressPrefix(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPort(int port) {
this.innerModel().withSourcePortRange(String.valueOf(port));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyPort() {
this.innerModel().withSourcePortRange("*");
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRange(int from, int to) {
this.innerModel().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRanges(String... ranges) {
this.innerModel().withSourcePortRanges(Arrays.asList(ranges));
this.innerModel().withSourcePortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddress(String cidr) {
this.innerModel().withDestinationAddressPrefix(cidr);
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddresses(String... addresses) {
this.innerModel().withDestinationAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withDestinationAddressPrefix(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyAddress() {
this.innerModel().withDestinationAddressPrefix("*");
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPort(int port) {
this.innerModel().withDestinationPortRange(String.valueOf(port));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyPort() {
this.innerModel().withDestinationPortRange("*");
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRange(int from, int to) {
this.innerModel().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRanges(String... ranges) {
this.innerModel().withDestinationPortRanges(Arrays.asList(ranges));
this.innerModel().withDestinationPortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withPriority(int priority) {
if (priority < 100 || priority > 4096) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"The priority number of a network security rule must be between 100 and 4096."));
}
this.innerModel().withPriority(priority);
return this;
}
@Override
public NetworkSecurityRuleImpl withDescription(String description) {
this.innerModel().withDescription(description);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) {
sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutSourceApplicationSecurityGroup(String id) {
sourceAsgs.remove(id);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String... ids) {
sourceAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) {
destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutDestinationApplicationSecurityGroup(String id) {
destinationAsgs.remove(id);
return this;
}
@Override
private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) {
this.innerModel().withDirection(direction);
return this;
}
private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) {
this.innerModel().withAccess(permission);
return this;
}
@Override
public NetworkSecurityGroupImpl attach() {
return this.parent().withRule(this);
}
@Override
public NetworkSecurityGroupImpl parent() {
innerModel().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values()));
innerModel().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values()));
return super.parent();
}
@Override
public String description() {
return this.innerModel().description();
}
} | class NetworkSecurityRuleImpl
extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup>
implements NetworkSecurityRule,
NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>,
NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>,
NetworkSecurityRule.Update {
private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>();
private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>();
private final ClientLogger logger = new ClientLogger(getClass());
NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) {
super(inner, parent);
if (inner.sourceApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) {
sourceAsgs.put(asg.id(), asg);
}
}
if (inner.destinationApplicationSecurityGroups() != null) {
for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) {
destinationAsgs.put(asg.id(), asg);
}
}
}
@Override
public String name() {
return this.innerModel().name();
}
@Override
public SecurityRuleDirection direction() {
return this.innerModel().direction();
}
@Override
public SecurityRuleProtocol protocol() {
return this.innerModel().protocol();
}
@Override
public SecurityRuleAccess access() {
return this.innerModel().access();
}
@Override
public String sourceAddressPrefix() {
return this.innerModel().sourceAddressPrefix();
}
@Override
public List<String> sourceAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().sourceAddressPrefixes());
}
@Override
public String sourcePortRange() {
return this.innerModel().sourcePortRange();
}
@Override
public List<String> sourcePortRanges() {
return Collections.unmodifiableList(innerModel().sourcePortRanges());
}
@Override
public String destinationAddressPrefix() {
return this.innerModel().destinationAddressPrefix();
}
@Override
public List<String> destinationAddressPrefixes() {
return Collections.unmodifiableList(this.innerModel().destinationAddressPrefixes());
}
@Override
public String destinationPortRange() {
return this.innerModel().destinationPortRange();
}
@Override
public List<String> destinationPortRanges() {
return Collections.unmodifiableList(innerModel().destinationPortRanges());
}
@Override
public int priority() {
return ResourceManagerUtils.toPrimitiveInt(this.innerModel().priority());
}
@Override
public Set<String> sourceApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(sourceAsgs.keySet());
}
@Override
public Set<String> destinationApplicationSecurityGroupIds() {
return Collections.unmodifiableSet(destinationAsgs.keySet());
}
@Override
public NetworkSecurityRuleImpl allowInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl allowOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW);
}
@Override
public NetworkSecurityRuleImpl denyInbound() {
return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl denyOutbound() {
return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY);
}
@Override
public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) {
this.innerModel().withProtocol(protocol);
return this;
}
@Override
public NetworkSecurityRuleImpl withAnyProtocol() {
return this.withProtocol(SecurityRuleProtocol.ASTERISK);
}
@Override
public NetworkSecurityRuleImpl fromAddress(String cidr) {
this.innerModel().withSourceAddressPrefix(cidr);
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyAddress() {
this.innerModel().withSourceAddressPrefix("*");
this.innerModel().withSourceAddressPrefixes(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAddresses(String... addresses) {
this.innerModel().withSourceAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withSourceAddressPrefix(null);
this.innerModel().withSourceApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPort(int port) {
this.innerModel().withSourcePortRange(String.valueOf(port));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromAnyPort() {
this.innerModel().withSourcePortRange("*");
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRange(int from, int to) {
this.innerModel().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withSourcePortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl fromPortRanges(String... ranges) {
this.innerModel().withSourcePortRanges(Arrays.asList(ranges));
this.innerModel().withSourcePortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddress(String cidr) {
this.innerModel().withDestinationAddressPrefix(cidr);
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAddresses(String... addresses) {
this.innerModel().withDestinationAddressPrefixes(Arrays.asList(addresses));
this.innerModel().withDestinationAddressPrefix(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyAddress() {
this.innerModel().withDestinationAddressPrefix("*");
this.innerModel().withDestinationAddressPrefixes(null);
this.innerModel().withDestinationApplicationSecurityGroups(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPort(int port) {
this.innerModel().withDestinationPortRange(String.valueOf(port));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toAnyPort() {
this.innerModel().withDestinationPortRange("*");
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRange(int from, int to) {
this.innerModel().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to));
this.innerModel().withDestinationPortRanges(null);
return this;
}
@Override
public NetworkSecurityRuleImpl toPortRanges(String... ranges) {
this.innerModel().withDestinationPortRanges(Arrays.asList(ranges));
this.innerModel().withDestinationPortRange(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withPriority(int priority) {
if (priority < 100 || priority > 4096) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"The priority number of a network security rule must be between 100 and 4096."));
}
this.innerModel().withPriority(priority);
return this;
}
@Override
public NetworkSecurityRuleImpl withDescription(String description) {
this.innerModel().withDescription(description);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) {
sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutSourceApplicationSecurityGroup(String id) {
sourceAsgs.remove(id);
return this;
}
@Override
public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String... ids) {
sourceAsgs = Arrays.stream(ids)
.collect(Collectors.toMap(Function.identity(), id -> new ApplicationSecurityGroupInner().withId(id)));
innerModel().withSourceAddressPrefix(null);
innerModel().withSourceAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) {
destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id));
innerModel().withDestinationAddressPrefix(null);
innerModel().withDestinationAddressPrefixes(null);
return this;
}
@Override
public NetworkSecurityRuleImpl withoutDestinationApplicationSecurityGroup(String id) {
destinationAsgs.remove(id);
return this;
}
@Override
private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) {
this.innerModel().withDirection(direction);
return this;
}
private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) {
this.innerModel().withAccess(permission);
return this;
}
@Override
public NetworkSecurityGroupImpl attach() {
return this.parent().withRule(this);
}
@Override
public NetworkSecurityGroupImpl parent() {
innerModel().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values()));
innerModel().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values()));
return super.parent();
}
@Override
public String description() {
return this.innerModel().description();
}
} |
Can you set this to operationTimeout in ms? So it's configurable in some way. or creating a constant that can be referenced. | protected void addTransportLayers(Event event, TransportInternal transport) {
transport.setIdleTimeout(60_000);
final SslDomain sslDomain = Proton.sslDomain();
sslDomain.init(SslDomain.Mode.CLIENT);
final SslDomain.VerifyMode verifyMode = connectionOptions.getSslVerifyMode();
final SSLContext defaultSslContext;
if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
defaultSslContext = null;
} else {
try {
defaultSslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new RuntimeException(
"Default SSL algorithm not found in JRE. Please check your JRE setup.", e));
}
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER_NAME) {
final StrictTlsContextSpi serviceProvider = new StrictTlsContextSpi(defaultSslContext);
final SSLContext context = new StrictTlsContext(serviceProvider, defaultSslContext.getProvider(),
defaultSslContext.getProtocol());
sslDomain.setSslContext(context);
transport.ssl(sslDomain, peerDetails);
return;
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER) {
sslDomain.setSslContext(defaultSslContext);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
} else if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
logger.warning("connectionId[{}] '{}' is not secure.", getConnectionId(), verifyMode);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.ANONYMOUS_PEER);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"verifyMode is not supported: " + verifyMode));
}
transport.ssl(sslDomain);
} | transport.setIdleTimeout(60_000); | protected void addTransportLayers(Event event, TransportInternal transport) {
transport.setIdleTimeout(CONNECTION_IDLE_TIMEOUT);
final SslDomain sslDomain = Proton.sslDomain();
sslDomain.init(SslDomain.Mode.CLIENT);
final SslDomain.VerifyMode verifyMode = connectionOptions.getSslVerifyMode();
final SSLContext defaultSslContext;
if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
defaultSslContext = null;
} else {
try {
defaultSslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new RuntimeException(
"Default SSL algorithm not found in JRE. Please check your JRE setup.", e));
}
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER_NAME) {
final StrictTlsContextSpi serviceProvider = new StrictTlsContextSpi(defaultSslContext);
final SSLContext context = new StrictTlsContext(serviceProvider, defaultSslContext.getProvider(),
defaultSslContext.getProtocol());
sslDomain.setSslContext(context);
transport.ssl(sslDomain, peerDetails);
return;
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER) {
sslDomain.setSslContext(defaultSslContext);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
} else if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
logger.warning("connectionId[{}] '{}' is not secure.", getConnectionId(), verifyMode);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.ANONYMOUS_PEER);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"verifyMode is not supported: " + verifyMode));
}
transport.ssl(sslDomain);
} | class ConnectionHandler extends Handler {
public static final int AMQPS_PORT = 5671;
static final Symbol PRODUCT = Symbol.valueOf("product");
static final Symbol VERSION = Symbol.valueOf("version");
static final Symbol PLATFORM = Symbol.valueOf("platform");
static final Symbol FRAMEWORK = Symbol.valueOf("framework");
static final Symbol USER_AGENT = Symbol.valueOf("user-agent");
static final int MAX_FRAME_SIZE = 65536;
private final Map<String, Object> connectionProperties;
private final ConnectionOptions connectionOptions;
private final SslPeerDetails peerDetails;
/**
* Creates a handler that handles proton-j's connection events.
*
* @param connectionId Identifier for this connection.
* @param connectionOptions Options used when creating the AMQP connection.
*/
public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions,
SslPeerDetails peerDetails) {
super(connectionId,
Objects.requireNonNull(connectionOptions, "'connectionOptions' cannot be null.").getHostname(),
new ClientLogger(ConnectionHandler.class));
add(new Handshaker());
this.connectionOptions = connectionOptions;
this.connectionProperties = new HashMap<>();
this.connectionProperties.put(PRODUCT.toString(), connectionOptions.getProduct());
this.connectionProperties.put(VERSION.toString(), connectionOptions.getClientVersion());
this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO);
this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO);
final ClientOptions clientOptions = connectionOptions.getClientOptions();
final String applicationId = !CoreUtils.isNullOrEmpty(clientOptions.getApplicationId())
? clientOptions.getApplicationId()
: null;
final String userAgent = UserAgentUtil.toUserAgentString(applicationId, connectionOptions.getProduct(),
connectionOptions.getClientVersion(), null);
this.connectionProperties.put(USER_AGENT.toString(), userAgent);
this.peerDetails = Objects.requireNonNull(peerDetails, "'peerDetails' cannot be null.");
}
/**
* Gets properties to add when creating AMQP connection.
*
* @return A map of properties to add when creating AMQP connection.
*/
public Map<String, Object> getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the port used when opening connection.
*
* @return The port used to open connection.
*/
public int getProtocolPort() {
return connectionOptions.getPort();
}
/**
* Gets the max frame size for this connection.
*
* @return The max frame size for this connection.
*/
public int getMaxFrameSize() {
return MAX_FRAME_SIZE;
}
/**
* Configures the SSL transport layer for the connection based on the {@link ConnectionOptions
*
* @param event The proton-j event.
* @param transport Transport to add layers to.
*/
@Override
public void onConnectionInit(Event event) {
logger.info("onConnectionInit connectionId[{}] hostname[{}] amqpHostname[{}]",
getConnectionId(), getHostname(), connectionOptions.getFullyQualifiedNamespace());
final Connection connection = event.getConnection();
if (connection == null) {
logger.warning("connectionId[{}] Underlying connection is null. Should not be possible.");
close();
return;
}
connection.setHostname(connectionOptions.getFullyQualifiedNamespace());
connection.setContainer(getConnectionId());
final Map<Symbol, Object> properties = new HashMap<>();
connectionProperties.forEach((key, value) -> properties.put(Symbol.getSymbol(key), value));
connection.setProperties(properties);
connection.open();
}
@Override
public void onConnectionBound(Event event) {
final Transport transport = event.getTransport();
logger.info("onConnectionBound connectionId[{}] hostname[{}] peerDetails[{}:{}]", getConnectionId(),
getHostname(), peerDetails.getHostname(), peerDetails.getPort());
this.addTransportLayers(event, (TransportInternal) transport);
final Connection connection = event.getConnection();
if (connection != null) {
onNext(connection.getRemoteState());
}
}
@Override
public void onConnectionUnbound(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionUnbound hostname[{}], connectionId[{}], state[{}], remoteState[{}]",
connection.getHostname(), getConnectionId(), connection.getLocalState(), connection.getRemoteState());
if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
connection.free();
}
close();
}
@Override
public void onTransportError(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.warning("onTransportError hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
transport.unbind();
}
@Override
public void onTransportClosed(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.info("onTransportClosed hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
}
@Override
public void onConnectionLocalOpen(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalOpen", connection, error);
}
@Override
public void onConnectionRemoteOpen(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionRemoteOpen hostname[{}], connectionId[{}], remoteContainer[{}]",
connection.getHostname(), getConnectionId(), connection.getRemoteContainer());
onNext(connection.getRemoteState());
}
@Override
public void onConnectionLocalClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalClose", connection, error);
if (connection.getRemoteState() == EndpointState.CLOSED) {
final Transport transport = connection.getTransport();
if (transport != null) {
transport.unbind();
}
}
}
@Override
public void onConnectionRemoteClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getRemoteCondition();
logErrorCondition("onConnectionRemoteClose", connection, error);
if (error == null) {
onNext(connection.getRemoteState());
} else {
notifyErrorContext(connection, error);
}
}
@Override
public void onConnectionFinal(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionFinal", connection, error);
onNext(EndpointState.CLOSED);
close();
}
public AmqpErrorContext getErrorContext() {
return new AmqpErrorContext(getHostname());
}
private void notifyErrorContext(Connection connection, ErrorCondition condition) {
if (connection == null || connection.getRemoteState() == EndpointState.CLOSED) {
return;
}
if (condition == null) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: notifyErrorContext does not have an ErrorCondition.", getConnectionId())));
}
final Throwable exception = ExceptionUtil.toException(condition.getCondition().toString(),
condition.getDescription(), getErrorContext());
onError(exception);
}
private void logErrorCondition(String eventName, Connection connection, ErrorCondition error) {
logger.info("{} connectionId[{}] hostname[{}] errorCondition[{}] errorDescription[{}]",
eventName,
getConnectionId(),
connection.getHostname(),
error != null ? error.getCondition() : ClientConstants.NOT_APPLICABLE,
error != null ? error.getDescription() : ClientConstants.NOT_APPLICABLE);
}
} | class ConnectionHandler extends Handler {
public static final int AMQPS_PORT = 5671;
static final Symbol PRODUCT = Symbol.valueOf("product");
static final Symbol VERSION = Symbol.valueOf("version");
static final Symbol PLATFORM = Symbol.valueOf("platform");
static final Symbol FRAMEWORK = Symbol.valueOf("framework");
static final Symbol USER_AGENT = Symbol.valueOf("user-agent");
static final int MAX_FRAME_SIZE = 65536;
static final int CONNECTION_IDLE_TIMEOUT = 60_000;
private final Map<String, Object> connectionProperties;
private final ConnectionOptions connectionOptions;
private final SslPeerDetails peerDetails;
/**
* Creates a handler that handles proton-j's connection events.
*
* @param connectionId Identifier for this connection.
* @param connectionOptions Options used when creating the AMQP connection.
*/
public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions,
SslPeerDetails peerDetails) {
super(connectionId,
Objects.requireNonNull(connectionOptions, "'connectionOptions' cannot be null.").getHostname(),
new ClientLogger(ConnectionHandler.class));
add(new Handshaker());
this.connectionOptions = connectionOptions;
this.connectionProperties = new HashMap<>();
this.connectionProperties.put(PRODUCT.toString(), connectionOptions.getProduct());
this.connectionProperties.put(VERSION.toString(), connectionOptions.getClientVersion());
this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO);
this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO);
final ClientOptions clientOptions = connectionOptions.getClientOptions();
final String applicationId = !CoreUtils.isNullOrEmpty(clientOptions.getApplicationId())
? clientOptions.getApplicationId()
: null;
final String userAgent = UserAgentUtil.toUserAgentString(applicationId, connectionOptions.getProduct(),
connectionOptions.getClientVersion(), null);
this.connectionProperties.put(USER_AGENT.toString(), userAgent);
this.peerDetails = Objects.requireNonNull(peerDetails, "'peerDetails' cannot be null.");
}
/**
* Gets properties to add when creating AMQP connection.
*
* @return A map of properties to add when creating AMQP connection.
*/
public Map<String, Object> getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the port used when opening connection.
*
* @return The port used to open connection.
*/
public int getProtocolPort() {
return connectionOptions.getPort();
}
/**
* Gets the max frame size for this connection.
*
* @return The max frame size for this connection.
*/
public int getMaxFrameSize() {
return MAX_FRAME_SIZE;
}
/**
* Configures the SSL transport layer for the connection based on the {@link ConnectionOptions
*
* @param event The proton-j event.
* @param transport Transport to add layers to.
*/
@Override
public void onConnectionInit(Event event) {
logger.info("onConnectionInit connectionId[{}] hostname[{}] amqpHostname[{}]",
getConnectionId(), getHostname(), connectionOptions.getFullyQualifiedNamespace());
final Connection connection = event.getConnection();
if (connection == null) {
logger.warning("connectionId[{}] Underlying connection is null. Should not be possible.");
close();
return;
}
connection.setHostname(connectionOptions.getFullyQualifiedNamespace());
connection.setContainer(getConnectionId());
final Map<Symbol, Object> properties = new HashMap<>();
connectionProperties.forEach((key, value) -> properties.put(Symbol.getSymbol(key), value));
connection.setProperties(properties);
connection.open();
}
@Override
public void onConnectionBound(Event event) {
final Transport transport = event.getTransport();
logger.info("onConnectionBound connectionId[{}] hostname[{}] peerDetails[{}:{}]", getConnectionId(),
getHostname(), peerDetails.getHostname(), peerDetails.getPort());
this.addTransportLayers(event, (TransportInternal) transport);
final Connection connection = event.getConnection();
if (connection != null) {
onNext(connection.getRemoteState());
}
}
@Override
public void onConnectionUnbound(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionUnbound hostname[{}], connectionId[{}], state[{}], remoteState[{}]",
connection.getHostname(), getConnectionId(), connection.getLocalState(), connection.getRemoteState());
if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
connection.free();
}
close();
}
@Override
public void onTransportError(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.warning("onTransportError hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
transport.unbind();
}
@Override
public void onTransportClosed(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.info("onTransportClosed hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
}
@Override
public void onConnectionLocalOpen(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalOpen", connection, error);
}
@Override
public void onConnectionRemoteOpen(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionRemoteOpen hostname[{}], connectionId[{}], remoteContainer[{}]",
connection.getHostname(), getConnectionId(), connection.getRemoteContainer());
onNext(connection.getRemoteState());
}
@Override
public void onConnectionLocalClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalClose", connection, error);
if (connection.getRemoteState() == EndpointState.CLOSED) {
final Transport transport = connection.getTransport();
if (transport != null) {
transport.unbind();
}
}
}
@Override
public void onConnectionRemoteClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getRemoteCondition();
logErrorCondition("onConnectionRemoteClose", connection, error);
if (error == null) {
onNext(connection.getRemoteState());
} else {
notifyErrorContext(connection, error);
}
}
@Override
public void onConnectionFinal(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionFinal", connection, error);
onNext(EndpointState.CLOSED);
close();
}
public AmqpErrorContext getErrorContext() {
return new AmqpErrorContext(getHostname());
}
private void notifyErrorContext(Connection connection, ErrorCondition condition) {
if (connection == null || connection.getRemoteState() == EndpointState.CLOSED) {
return;
}
if (condition == null) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: notifyErrorContext does not have an ErrorCondition.", getConnectionId())));
}
final Throwable exception = ExceptionUtil.toException(condition.getCondition().toString(),
condition.getDescription(), getErrorContext());
onError(exception);
}
private void logErrorCondition(String eventName, Connection connection, ErrorCondition error) {
logger.info("{} connectionId[{}] hostname[{}] errorCondition[{}] errorDescription[{}]",
eventName,
getConnectionId(),
connection.getHostname(),
error != null ? error.getCondition() : ClientConstants.NOT_APPLICABLE,
error != null ? error.getDescription() : ClientConstants.NOT_APPLICABLE);
}
} |
Users might set a short operationTimeout, which as an adverse impact on the established connection. So a separate value might be better. Added constant CONNECTION_IDLE_TIMEOUT | protected void addTransportLayers(Event event, TransportInternal transport) {
transport.setIdleTimeout(60_000);
final SslDomain sslDomain = Proton.sslDomain();
sslDomain.init(SslDomain.Mode.CLIENT);
final SslDomain.VerifyMode verifyMode = connectionOptions.getSslVerifyMode();
final SSLContext defaultSslContext;
if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
defaultSslContext = null;
} else {
try {
defaultSslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new RuntimeException(
"Default SSL algorithm not found in JRE. Please check your JRE setup.", e));
}
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER_NAME) {
final StrictTlsContextSpi serviceProvider = new StrictTlsContextSpi(defaultSslContext);
final SSLContext context = new StrictTlsContext(serviceProvider, defaultSslContext.getProvider(),
defaultSslContext.getProtocol());
sslDomain.setSslContext(context);
transport.ssl(sslDomain, peerDetails);
return;
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER) {
sslDomain.setSslContext(defaultSslContext);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
} else if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
logger.warning("connectionId[{}] '{}' is not secure.", getConnectionId(), verifyMode);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.ANONYMOUS_PEER);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"verifyMode is not supported: " + verifyMode));
}
transport.ssl(sslDomain);
} | transport.setIdleTimeout(60_000); | protected void addTransportLayers(Event event, TransportInternal transport) {
transport.setIdleTimeout(CONNECTION_IDLE_TIMEOUT);
final SslDomain sslDomain = Proton.sslDomain();
sslDomain.init(SslDomain.Mode.CLIENT);
final SslDomain.VerifyMode verifyMode = connectionOptions.getSslVerifyMode();
final SSLContext defaultSslContext;
if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
defaultSslContext = null;
} else {
try {
defaultSslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new RuntimeException(
"Default SSL algorithm not found in JRE. Please check your JRE setup.", e));
}
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER_NAME) {
final StrictTlsContextSpi serviceProvider = new StrictTlsContextSpi(defaultSslContext);
final SSLContext context = new StrictTlsContext(serviceProvider, defaultSslContext.getProvider(),
defaultSslContext.getProtocol());
sslDomain.setSslContext(context);
transport.ssl(sslDomain, peerDetails);
return;
}
if (verifyMode == SslDomain.VerifyMode.VERIFY_PEER) {
sslDomain.setSslContext(defaultSslContext);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
} else if (verifyMode == SslDomain.VerifyMode.ANONYMOUS_PEER) {
logger.warning("connectionId[{}] '{}' is not secure.", getConnectionId(), verifyMode);
sslDomain.setPeerAuthentication(SslDomain.VerifyMode.ANONYMOUS_PEER);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(
"verifyMode is not supported: " + verifyMode));
}
transport.ssl(sslDomain);
} | class ConnectionHandler extends Handler {
public static final int AMQPS_PORT = 5671;
static final Symbol PRODUCT = Symbol.valueOf("product");
static final Symbol VERSION = Symbol.valueOf("version");
static final Symbol PLATFORM = Symbol.valueOf("platform");
static final Symbol FRAMEWORK = Symbol.valueOf("framework");
static final Symbol USER_AGENT = Symbol.valueOf("user-agent");
static final int MAX_FRAME_SIZE = 65536;
private final Map<String, Object> connectionProperties;
private final ConnectionOptions connectionOptions;
private final SslPeerDetails peerDetails;
/**
* Creates a handler that handles proton-j's connection events.
*
* @param connectionId Identifier for this connection.
* @param connectionOptions Options used when creating the AMQP connection.
*/
public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions,
SslPeerDetails peerDetails) {
super(connectionId,
Objects.requireNonNull(connectionOptions, "'connectionOptions' cannot be null.").getHostname(),
new ClientLogger(ConnectionHandler.class));
add(new Handshaker());
this.connectionOptions = connectionOptions;
this.connectionProperties = new HashMap<>();
this.connectionProperties.put(PRODUCT.toString(), connectionOptions.getProduct());
this.connectionProperties.put(VERSION.toString(), connectionOptions.getClientVersion());
this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO);
this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO);
final ClientOptions clientOptions = connectionOptions.getClientOptions();
final String applicationId = !CoreUtils.isNullOrEmpty(clientOptions.getApplicationId())
? clientOptions.getApplicationId()
: null;
final String userAgent = UserAgentUtil.toUserAgentString(applicationId, connectionOptions.getProduct(),
connectionOptions.getClientVersion(), null);
this.connectionProperties.put(USER_AGENT.toString(), userAgent);
this.peerDetails = Objects.requireNonNull(peerDetails, "'peerDetails' cannot be null.");
}
/**
* Gets properties to add when creating AMQP connection.
*
* @return A map of properties to add when creating AMQP connection.
*/
public Map<String, Object> getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the port used when opening connection.
*
* @return The port used to open connection.
*/
public int getProtocolPort() {
return connectionOptions.getPort();
}
/**
* Gets the max frame size for this connection.
*
* @return The max frame size for this connection.
*/
public int getMaxFrameSize() {
return MAX_FRAME_SIZE;
}
/**
* Configures the SSL transport layer for the connection based on the {@link ConnectionOptions
*
* @param event The proton-j event.
* @param transport Transport to add layers to.
*/
@Override
public void onConnectionInit(Event event) {
logger.info("onConnectionInit connectionId[{}] hostname[{}] amqpHostname[{}]",
getConnectionId(), getHostname(), connectionOptions.getFullyQualifiedNamespace());
final Connection connection = event.getConnection();
if (connection == null) {
logger.warning("connectionId[{}] Underlying connection is null. Should not be possible.");
close();
return;
}
connection.setHostname(connectionOptions.getFullyQualifiedNamespace());
connection.setContainer(getConnectionId());
final Map<Symbol, Object> properties = new HashMap<>();
connectionProperties.forEach((key, value) -> properties.put(Symbol.getSymbol(key), value));
connection.setProperties(properties);
connection.open();
}
@Override
public void onConnectionBound(Event event) {
final Transport transport = event.getTransport();
logger.info("onConnectionBound connectionId[{}] hostname[{}] peerDetails[{}:{}]", getConnectionId(),
getHostname(), peerDetails.getHostname(), peerDetails.getPort());
this.addTransportLayers(event, (TransportInternal) transport);
final Connection connection = event.getConnection();
if (connection != null) {
onNext(connection.getRemoteState());
}
}
@Override
public void onConnectionUnbound(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionUnbound hostname[{}], connectionId[{}], state[{}], remoteState[{}]",
connection.getHostname(), getConnectionId(), connection.getLocalState(), connection.getRemoteState());
if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
connection.free();
}
close();
}
@Override
public void onTransportError(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.warning("onTransportError hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
transport.unbind();
}
@Override
public void onTransportClosed(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.info("onTransportClosed hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
}
@Override
public void onConnectionLocalOpen(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalOpen", connection, error);
}
@Override
public void onConnectionRemoteOpen(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionRemoteOpen hostname[{}], connectionId[{}], remoteContainer[{}]",
connection.getHostname(), getConnectionId(), connection.getRemoteContainer());
onNext(connection.getRemoteState());
}
@Override
public void onConnectionLocalClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalClose", connection, error);
if (connection.getRemoteState() == EndpointState.CLOSED) {
final Transport transport = connection.getTransport();
if (transport != null) {
transport.unbind();
}
}
}
@Override
public void onConnectionRemoteClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getRemoteCondition();
logErrorCondition("onConnectionRemoteClose", connection, error);
if (error == null) {
onNext(connection.getRemoteState());
} else {
notifyErrorContext(connection, error);
}
}
@Override
public void onConnectionFinal(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionFinal", connection, error);
onNext(EndpointState.CLOSED);
close();
}
public AmqpErrorContext getErrorContext() {
return new AmqpErrorContext(getHostname());
}
private void notifyErrorContext(Connection connection, ErrorCondition condition) {
if (connection == null || connection.getRemoteState() == EndpointState.CLOSED) {
return;
}
if (condition == null) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: notifyErrorContext does not have an ErrorCondition.", getConnectionId())));
}
final Throwable exception = ExceptionUtil.toException(condition.getCondition().toString(),
condition.getDescription(), getErrorContext());
onError(exception);
}
private void logErrorCondition(String eventName, Connection connection, ErrorCondition error) {
logger.info("{} connectionId[{}] hostname[{}] errorCondition[{}] errorDescription[{}]",
eventName,
getConnectionId(),
connection.getHostname(),
error != null ? error.getCondition() : ClientConstants.NOT_APPLICABLE,
error != null ? error.getDescription() : ClientConstants.NOT_APPLICABLE);
}
} | class ConnectionHandler extends Handler {
public static final int AMQPS_PORT = 5671;
static final Symbol PRODUCT = Symbol.valueOf("product");
static final Symbol VERSION = Symbol.valueOf("version");
static final Symbol PLATFORM = Symbol.valueOf("platform");
static final Symbol FRAMEWORK = Symbol.valueOf("framework");
static final Symbol USER_AGENT = Symbol.valueOf("user-agent");
static final int MAX_FRAME_SIZE = 65536;
static final int CONNECTION_IDLE_TIMEOUT = 60_000;
private final Map<String, Object> connectionProperties;
private final ConnectionOptions connectionOptions;
private final SslPeerDetails peerDetails;
/**
* Creates a handler that handles proton-j's connection events.
*
* @param connectionId Identifier for this connection.
* @param connectionOptions Options used when creating the AMQP connection.
*/
public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions,
SslPeerDetails peerDetails) {
super(connectionId,
Objects.requireNonNull(connectionOptions, "'connectionOptions' cannot be null.").getHostname(),
new ClientLogger(ConnectionHandler.class));
add(new Handshaker());
this.connectionOptions = connectionOptions;
this.connectionProperties = new HashMap<>();
this.connectionProperties.put(PRODUCT.toString(), connectionOptions.getProduct());
this.connectionProperties.put(VERSION.toString(), connectionOptions.getClientVersion());
this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO);
this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO);
final ClientOptions clientOptions = connectionOptions.getClientOptions();
final String applicationId = !CoreUtils.isNullOrEmpty(clientOptions.getApplicationId())
? clientOptions.getApplicationId()
: null;
final String userAgent = UserAgentUtil.toUserAgentString(applicationId, connectionOptions.getProduct(),
connectionOptions.getClientVersion(), null);
this.connectionProperties.put(USER_AGENT.toString(), userAgent);
this.peerDetails = Objects.requireNonNull(peerDetails, "'peerDetails' cannot be null.");
}
/**
* Gets properties to add when creating AMQP connection.
*
* @return A map of properties to add when creating AMQP connection.
*/
public Map<String, Object> getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the port used when opening connection.
*
* @return The port used to open connection.
*/
public int getProtocolPort() {
return connectionOptions.getPort();
}
/**
* Gets the max frame size for this connection.
*
* @return The max frame size for this connection.
*/
public int getMaxFrameSize() {
return MAX_FRAME_SIZE;
}
/**
* Configures the SSL transport layer for the connection based on the {@link ConnectionOptions
*
* @param event The proton-j event.
* @param transport Transport to add layers to.
*/
@Override
public void onConnectionInit(Event event) {
logger.info("onConnectionInit connectionId[{}] hostname[{}] amqpHostname[{}]",
getConnectionId(), getHostname(), connectionOptions.getFullyQualifiedNamespace());
final Connection connection = event.getConnection();
if (connection == null) {
logger.warning("connectionId[{}] Underlying connection is null. Should not be possible.");
close();
return;
}
connection.setHostname(connectionOptions.getFullyQualifiedNamespace());
connection.setContainer(getConnectionId());
final Map<Symbol, Object> properties = new HashMap<>();
connectionProperties.forEach((key, value) -> properties.put(Symbol.getSymbol(key), value));
connection.setProperties(properties);
connection.open();
}
@Override
public void onConnectionBound(Event event) {
final Transport transport = event.getTransport();
logger.info("onConnectionBound connectionId[{}] hostname[{}] peerDetails[{}:{}]", getConnectionId(),
getHostname(), peerDetails.getHostname(), peerDetails.getPort());
this.addTransportLayers(event, (TransportInternal) transport);
final Connection connection = event.getConnection();
if (connection != null) {
onNext(connection.getRemoteState());
}
}
@Override
public void onConnectionUnbound(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionUnbound hostname[{}], connectionId[{}], state[{}], remoteState[{}]",
connection.getHostname(), getConnectionId(), connection.getLocalState(), connection.getRemoteState());
if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
connection.free();
}
close();
}
@Override
public void onTransportError(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.warning("onTransportError hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
transport.unbind();
}
@Override
public void onTransportClosed(Event event) {
final Connection connection = event.getConnection();
final Transport transport = event.getTransport();
final ErrorCondition condition = transport.getCondition();
logger.info("onTransportClosed hostname[{}], connectionId[{}], error[{}]",
connection != null ? connection.getHostname() : ClientConstants.NOT_APPLICABLE,
getConnectionId(),
condition != null ? condition.getDescription() : ClientConstants.NOT_APPLICABLE);
if (connection != null) {
notifyErrorContext(connection, condition);
}
}
@Override
public void onConnectionLocalOpen(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalOpen", connection, error);
}
@Override
public void onConnectionRemoteOpen(Event event) {
final Connection connection = event.getConnection();
logger.info("onConnectionRemoteOpen hostname[{}], connectionId[{}], remoteContainer[{}]",
connection.getHostname(), getConnectionId(), connection.getRemoteContainer());
onNext(connection.getRemoteState());
}
@Override
public void onConnectionLocalClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionLocalClose", connection, error);
if (connection.getRemoteState() == EndpointState.CLOSED) {
final Transport transport = connection.getTransport();
if (transport != null) {
transport.unbind();
}
}
}
@Override
public void onConnectionRemoteClose(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getRemoteCondition();
logErrorCondition("onConnectionRemoteClose", connection, error);
if (error == null) {
onNext(connection.getRemoteState());
} else {
notifyErrorContext(connection, error);
}
}
@Override
public void onConnectionFinal(Event event) {
final Connection connection = event.getConnection();
final ErrorCondition error = connection.getCondition();
logErrorCondition("onConnectionFinal", connection, error);
onNext(EndpointState.CLOSED);
close();
}
public AmqpErrorContext getErrorContext() {
return new AmqpErrorContext(getHostname());
}
private void notifyErrorContext(Connection connection, ErrorCondition condition) {
if (connection == null || connection.getRemoteState() == EndpointState.CLOSED) {
return;
}
if (condition == null) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: notifyErrorContext does not have an ErrorCondition.", getConnectionId())));
}
final Throwable exception = ExceptionUtil.toException(condition.getCondition().toString(),
condition.getDescription(), getErrorContext());
onError(exception);
}
private void logErrorCondition(String eventName, Connection connection, ErrorCondition error) {
logger.info("{} connectionId[{}] hostname[{}] errorCondition[{}] errorDescription[{}]",
eventName,
getConnectionId(),
connection.getHostname(),
error != null ? error.getCondition() : ClientConstants.NOT_APPLICABLE,
error != null ? error.getDescription() : ClientConstants.NOT_APPLICABLE);
}
} |
sample here | public void canCreateClusterWithSpotVM() throws Exception {
String aksName = generateRandomResourceName("aks", 15);
String dnsPrefix = generateRandomResourceName("dns", 10);
String agentPoolName = generateRandomResourceName("ap0", 10);
String agentPoolName1 = generateRandomResourceName("ap1", 10);
String agentPoolName2 = generateRandomResourceName("ap2", 10);
KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName)
.withRegion(Region.US_CENTRAL)
.withExistingResourceGroup(rgName)
.withDefaultVersion()
.withRootUsername("testaks")
.withSshKey(SSH_KEY)
.withSystemAssignedManagedServiceIdentity()
.defineAgentPool(agentPoolName)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2)
.withAgentPoolVirtualMachineCount(1)
.withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.attach()
.defineAgentPool(agentPoolName1)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.withSpotPriorityVirtualMachine()
.attach()
.withDnsPrefix("mp1" + dnsPrefix)
.create();
System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8));
KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName);
Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR);
KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile1.virtualMachinePriority());
Assertions.assertEquals(ScaleSetEvictionPolicy.DELETE, agentPoolProfile1.virtualMachineEvictionPolicy());
Assertions.assertEquals(-1.0, agentPoolProfile1.virtualMachineMaximumPrice());
kubernetesCluster.update()
.defineAgentPool(agentPoolName2)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.DEALLOCATE)
.withVirtualMachineMaximumPrice(100.0)
.attach()
.apply();
KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2);
Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile2.virtualMachinePriority());
Assertions.assertEquals(ScaleSetEvictionPolicy.DEALLOCATE, agentPoolProfile2.virtualMachineEvictionPolicy());
Assertions.assertEquals(100.0, agentPoolProfile2.virtualMachineMaximumPrice());
} | .attach() | public void canCreateClusterWithSpotVM() throws Exception {
String aksName = generateRandomResourceName("aks", 15);
String dnsPrefix = generateRandomResourceName("dns", 10);
String agentPoolName = generateRandomResourceName("ap0", 10);
String agentPoolName1 = generateRandomResourceName("ap1", 10);
String agentPoolName2 = generateRandomResourceName("ap2", 10);
KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName)
.withRegion(Region.US_CENTRAL)
.withExistingResourceGroup(rgName)
.withDefaultVersion()
.withRootUsername("testaks")
.withSshKey(SSH_KEY)
.withSystemAssignedManagedServiceIdentity()
.defineAgentPool(agentPoolName)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2)
.withAgentPoolVirtualMachineCount(1)
.withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.attach()
.defineAgentPool(agentPoolName1)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.withSpotPriorityVirtualMachine()
.attach()
.withDnsPrefix("mp1" + dnsPrefix)
.create();
System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8));
KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName);
Assertions.assertTrue(agentPoolProfile.virtualMachinePriority() == null || agentPoolProfile.virtualMachinePriority() == ScaleSetPriority.REGULAR);
KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile1.virtualMachinePriority());
Assertions.assertEquals(ScaleSetEvictionPolicy.DELETE, agentPoolProfile1.virtualMachineEvictionPolicy());
Assertions.assertEquals(-1.0, agentPoolProfile1.virtualMachineMaximumPrice());
kubernetesCluster.update()
.defineAgentPool(agentPoolName2)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.withSpotPriorityVirtualMachine(ScaleSetEvictionPolicy.DEALLOCATE)
.withVirtualMachineMaximumPrice(100.0)
.attach()
.apply();
KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2);
Assertions.assertEquals(ScaleSetPriority.SPOT, agentPoolProfile2.virtualMachinePriority());
Assertions.assertEquals(ScaleSetEvictionPolicy.DEALLOCATE, agentPoolProfile2.virtualMachineEvictionPolicy());
Assertions.assertEquals(100.0, agentPoolProfile2.virtualMachineMaximumPrice());
} | class KubernetesClustersTests extends ContainerServiceManagementTest {
private static final String SSH_KEY = sshPublicKey();
@Test
public void canCRUDKubernetesCluster() throws Exception {
String aksName = generateRandomResourceName("aks", 15);
String dnsPrefix = generateRandomResourceName("dns", 10);
String agentPoolName = generateRandomResourceName("ap0", 10);
String agentPoolName1 = generateRandomResourceName("ap1", 10);
String agentPoolName2 = generateRandomResourceName("ap2", 10);
String servicePrincipalClientId = "spId";
String servicePrincipalSecret = "spSecret";
String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2");
if (envSecondaryServicePrincipal == null
|| envSecondaryServicePrincipal.isEmpty()
|| !(new File(envSecondaryServicePrincipal).exists())) {
envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION");
}
if (!isPlaybackMode()) {
HashMap<String, String> credentialsMap = parseAuthFile(envSecondaryServicePrincipal);
servicePrincipalClientId = credentialsMap.get("clientId");
servicePrincipalSecret = credentialsMap.get("clientSecret");
}
KubernetesCluster kubernetesCluster =
containerServiceManager
.kubernetesClusters()
.define(aksName)
.withRegion(Region.US_CENTRAL)
.withExistingResourceGroup(rgName)
.withDefaultVersion()
.withRootUsername("testaks")
.withSshKey(SSH_KEY)
.withServicePrincipalClientId(servicePrincipalClientId)
.withServicePrincipalSecret(servicePrincipalSecret)
.defineAgentPool(agentPoolName)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2)
.withAgentPoolVirtualMachineCount(1)
.withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.attach()
.defineAgentPool(agentPoolName1)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.attach()
.withDnsPrefix("mp1" + dnsPrefix)
.withTag("tag1", "value1")
.create();
Assertions.assertNotNull(kubernetesCluster.id());
Assertions.assertEquals(Region.US_CENTRAL, kubernetesCluster.region());
Assertions.assertEquals("testaks", kubernetesCluster.linuxRootUsername());
Assertions.assertEquals(2, kubernetesCluster.agentPools().size());
KubernetesClusterAgentPool agentPool = kubernetesCluster.agentPools().get(agentPoolName);
Assertions.assertNotNull(agentPool);
Assertions.assertEquals(1, agentPool.count());
Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_D2_V2, agentPool.vmSize());
Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type());
Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode());
agentPool = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertNotNull(agentPool);
Assertions.assertEquals(1, agentPool.count());
Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, agentPool.vmSize());
Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type());
Assertions.assertNotNull(kubernetesCluster.tags().get("tag1"));
kubernetesCluster =
kubernetesCluster
.update()
.updateAgentPool(agentPoolName1)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.withAgentPoolVirtualMachineCount(5)
.parent()
.defineAgentPool(agentPoolName2)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.attach()
.withTag("tag2", "value2")
.withTag("tag3", "value3")
.withoutTag("tag1")
.apply();
Assertions.assertEquals(3, kubernetesCluster.agentPools().size());
agentPool = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertEquals(5, agentPool.count());
Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode());
agentPool = kubernetesCluster.agentPools().get(agentPoolName2);
Assertions.assertNotNull(agentPool);
Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, agentPool.vmSize());
Assertions.assertEquals(1, agentPool.count());
Assertions.assertEquals("value2", kubernetesCluster.tags().get("tag2"));
Assertions.assertFalse(kubernetesCluster.tags().containsKey("tag1"));
}
@Test
public void canAutoScaleKubernetesCluster() throws Exception {
String aksName = generateRandomResourceName("aks", 15);
String dnsPrefix = generateRandomResourceName("dns", 10);
String agentPoolName = generateRandomResourceName("ap0", 10);
String agentPoolName1 = generateRandomResourceName("ap1", 10);
String agentPoolName2 = generateRandomResourceName("ap2", 10);
String agentPoolName3 = generateRandomResourceName("ap2", 10);
String servicePrincipalClientId = "spId";
String servicePrincipalSecret = "spSecret";
String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2");
if (envSecondaryServicePrincipal == null
|| envSecondaryServicePrincipal.isEmpty()
|| !(new File(envSecondaryServicePrincipal).exists())) {
envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION");
}
if (!isPlaybackMode()) {
HashMap<String, String> credentialsMap = parseAuthFile(envSecondaryServicePrincipal);
servicePrincipalClientId = credentialsMap.get("clientId");
servicePrincipalSecret = credentialsMap.get("clientSecret");
}
KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName)
.withRegion(Region.US_CENTRAL)
.withExistingResourceGroup(rgName)
.withDefaultVersion()
.withRootUsername("testaks")
.withSshKey(SSH_KEY)
.withServicePrincipalClientId(servicePrincipalClientId)
.withServicePrincipalSecret(servicePrincipalSecret)
.defineAgentPool(agentPoolName)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2)
.withAgentPoolVirtualMachineCount(3)
.withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.withAvailabilityZones(1, 2, 3)
.attach()
.defineAgentPool(agentPoolName1)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.withAutoScaling(1, 3)
.withNodeLabels(ImmutableMap.of("environment", "dev", "app.1", "spring"))
.withNodeTaints(ImmutableList.of("key=value:NoSchedule"))
.attach()
.defineAgentPool(agentPoolName2)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(0)
.withMaxPodsCount(10)
.attach()
.withDnsPrefix("mp1" + dnsPrefix)
.withAutoScalerProfile(new ManagedClusterPropertiesAutoScalerProfile().withScanInterval("30s"))
.create();
System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8));
Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code());
KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName);
Assertions.assertEquals(3, agentPoolProfile.nodeSize());
Assertions.assertFalse(agentPoolProfile.isAutoScalingEnabled());
Assertions.assertEquals(Arrays.asList("1", "2", "3"), agentPoolProfile.availabilityZones());
Assertions.assertEquals(Code.RUNNING, agentPoolProfile.powerState().code());
KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertEquals(1, agentPoolProfile1.nodeSize());
Assertions.assertTrue(agentPoolProfile1.isAutoScalingEnabled());
Assertions.assertEquals(1, agentPoolProfile1.minimumNodeSize());
Assertions.assertEquals(3, agentPoolProfile1.maximumNodeSize());
Assertions.assertEquals(ImmutableMap.of("environment", "dev", "app.1", "spring"), agentPoolProfile1.nodeLabels());
Assertions.assertEquals("key=value:NoSchedule", agentPoolProfile1.nodeTaints().iterator().next());
KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2);
Assertions.assertEquals(0, agentPoolProfile2.nodeSize());
Assertions.assertEquals(10, agentPoolProfile2.maximumPodsPerNode());
kubernetesCluster.update()
.updateAgentPool(agentPoolName1)
.withoutAutoScaling()
.parent()
.apply();
kubernetesCluster.update()
.withoutAgentPool(agentPoolName1)
.withoutAgentPool(agentPoolName2)
.defineAgentPool(agentPoolName3)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(0)
.attach()
.apply();
Assertions.assertEquals(2, kubernetesCluster.agentPools().size());
KubernetesClusterAgentPool agentPoolProfile3 = kubernetesCluster.agentPools().get(agentPoolName3);
Assertions.assertEquals(0, agentPoolProfile3.nodeSize());
}
@Test
/**
* Parse azure auth to hashmap
*
* @param authFilename the azure auth location
* @return all fields in azure auth json
* @throws Exception exception
*/
private static HashMap<String, String> parseAuthFile(String authFilename) throws Exception {
String content = new String(Files.readAllBytes(new File(authFilename).toPath()), StandardCharsets.UTF_8).trim();
HashMap<String, String> auth = new HashMap<>();
if (isJsonBased(content)) {
auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON);
} else {
Properties authSettings = new Properties();
FileInputStream credentialsFileStream = new FileInputStream(new File(authFilename));
authSettings.load(credentialsFileStream);
credentialsFileStream.close();
for (final String authName : authSettings.stringPropertyNames()) {
auth.put(authName, authSettings.getProperty(authName));
}
}
return auth;
}
private static boolean isJsonBased(String content) {
return content.startsWith("{");
}
} | class KubernetesClustersTests extends ContainerServiceManagementTest {
private static final String SSH_KEY = sshPublicKey();
@Test
public void canCRUDKubernetesCluster() throws Exception {
String aksName = generateRandomResourceName("aks", 15);
String dnsPrefix = generateRandomResourceName("dns", 10);
String agentPoolName = generateRandomResourceName("ap0", 10);
String agentPoolName1 = generateRandomResourceName("ap1", 10);
String agentPoolName2 = generateRandomResourceName("ap2", 10);
String servicePrincipalClientId = "spId";
String servicePrincipalSecret = "spSecret";
String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2");
if (envSecondaryServicePrincipal == null
|| envSecondaryServicePrincipal.isEmpty()
|| !(new File(envSecondaryServicePrincipal).exists())) {
envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION");
}
if (!isPlaybackMode()) {
HashMap<String, String> credentialsMap = parseAuthFile(envSecondaryServicePrincipal);
servicePrincipalClientId = credentialsMap.get("clientId");
servicePrincipalSecret = credentialsMap.get("clientSecret");
}
KubernetesCluster kubernetesCluster =
containerServiceManager
.kubernetesClusters()
.define(aksName)
.withRegion(Region.US_CENTRAL)
.withExistingResourceGroup(rgName)
.withDefaultVersion()
.withRootUsername("testaks")
.withSshKey(SSH_KEY)
.withServicePrincipalClientId(servicePrincipalClientId)
.withServicePrincipalSecret(servicePrincipalSecret)
.defineAgentPool(agentPoolName)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2)
.withAgentPoolVirtualMachineCount(1)
.withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.attach()
.defineAgentPool(agentPoolName1)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.attach()
.withDnsPrefix("mp1" + dnsPrefix)
.withTag("tag1", "value1")
.create();
Assertions.assertNotNull(kubernetesCluster.id());
Assertions.assertEquals(Region.US_CENTRAL, kubernetesCluster.region());
Assertions.assertEquals("testaks", kubernetesCluster.linuxRootUsername());
Assertions.assertEquals(2, kubernetesCluster.agentPools().size());
KubernetesClusterAgentPool agentPool = kubernetesCluster.agentPools().get(agentPoolName);
Assertions.assertNotNull(agentPool);
Assertions.assertEquals(1, agentPool.count());
Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_D2_V2, agentPool.vmSize());
Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type());
Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode());
agentPool = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertNotNull(agentPool);
Assertions.assertEquals(1, agentPool.count());
Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, agentPool.vmSize());
Assertions.assertEquals(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS, agentPool.type());
Assertions.assertNotNull(kubernetesCluster.tags().get("tag1"));
kubernetesCluster =
kubernetesCluster
.update()
.updateAgentPool(agentPoolName1)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.withAgentPoolVirtualMachineCount(5)
.parent()
.defineAgentPool(agentPoolName2)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.attach()
.withTag("tag2", "value2")
.withTag("tag3", "value3")
.withoutTag("tag1")
.apply();
Assertions.assertEquals(3, kubernetesCluster.agentPools().size());
agentPool = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertEquals(5, agentPool.count());
Assertions.assertEquals(AgentPoolMode.SYSTEM, agentPool.mode());
agentPool = kubernetesCluster.agentPools().get(agentPoolName2);
Assertions.assertNotNull(agentPool);
Assertions.assertEquals(ContainerServiceVMSizeTypes.STANDARD_A2_V2, agentPool.vmSize());
Assertions.assertEquals(1, agentPool.count());
Assertions.assertEquals("value2", kubernetesCluster.tags().get("tag2"));
Assertions.assertFalse(kubernetesCluster.tags().containsKey("tag1"));
}
@Test
public void canAutoScaleKubernetesCluster() throws Exception {
String aksName = generateRandomResourceName("aks", 15);
String dnsPrefix = generateRandomResourceName("dns", 10);
String agentPoolName = generateRandomResourceName("ap0", 10);
String agentPoolName1 = generateRandomResourceName("ap1", 10);
String agentPoolName2 = generateRandomResourceName("ap2", 10);
String agentPoolName3 = generateRandomResourceName("ap2", 10);
String servicePrincipalClientId = "spId";
String servicePrincipalSecret = "spSecret";
String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2");
if (envSecondaryServicePrincipal == null
|| envSecondaryServicePrincipal.isEmpty()
|| !(new File(envSecondaryServicePrincipal).exists())) {
envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION");
}
if (!isPlaybackMode()) {
HashMap<String, String> credentialsMap = parseAuthFile(envSecondaryServicePrincipal);
servicePrincipalClientId = credentialsMap.get("clientId");
servicePrincipalSecret = credentialsMap.get("clientSecret");
}
KubernetesCluster kubernetesCluster = containerServiceManager.kubernetesClusters().define(aksName)
.withRegion(Region.US_CENTRAL)
.withExistingResourceGroup(rgName)
.withDefaultVersion()
.withRootUsername("testaks")
.withSshKey(SSH_KEY)
.withServicePrincipalClientId(servicePrincipalClientId)
.withServicePrincipalSecret(servicePrincipalSecret)
.defineAgentPool(agentPoolName)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2)
.withAgentPoolVirtualMachineCount(3)
.withAgentPoolType(AgentPoolType.VIRTUAL_MACHINE_SCALE_SETS)
.withAgentPoolMode(AgentPoolMode.SYSTEM)
.withAvailabilityZones(1, 2, 3)
.attach()
.defineAgentPool(agentPoolName1)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(1)
.withAutoScaling(1, 3)
.withNodeLabels(ImmutableMap.of("environment", "dev", "app.1", "spring"))
.withNodeTaints(ImmutableList.of("key=value:NoSchedule"))
.attach()
.defineAgentPool(agentPoolName2)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(0)
.withMaxPodsCount(10)
.attach()
.withDnsPrefix("mp1" + dnsPrefix)
.withAutoScalerProfile(new ManagedClusterPropertiesAutoScalerProfile().withScanInterval("30s"))
.create();
System.out.println(new String(kubernetesCluster.adminKubeConfigContent(), StandardCharsets.UTF_8));
Assertions.assertEquals(Code.RUNNING, kubernetesCluster.powerState().code());
KubernetesClusterAgentPool agentPoolProfile = kubernetesCluster.agentPools().get(agentPoolName);
Assertions.assertEquals(3, agentPoolProfile.nodeSize());
Assertions.assertFalse(agentPoolProfile.isAutoScalingEnabled());
Assertions.assertEquals(Arrays.asList("1", "2", "3"), agentPoolProfile.availabilityZones());
Assertions.assertEquals(Code.RUNNING, agentPoolProfile.powerState().code());
KubernetesClusterAgentPool agentPoolProfile1 = kubernetesCluster.agentPools().get(agentPoolName1);
Assertions.assertEquals(1, agentPoolProfile1.nodeSize());
Assertions.assertTrue(agentPoolProfile1.isAutoScalingEnabled());
Assertions.assertEquals(1, agentPoolProfile1.minimumNodeSize());
Assertions.assertEquals(3, agentPoolProfile1.maximumNodeSize());
Assertions.assertEquals(ImmutableMap.of("environment", "dev", "app.1", "spring"), agentPoolProfile1.nodeLabels());
Assertions.assertEquals("key=value:NoSchedule", agentPoolProfile1.nodeTaints().iterator().next());
KubernetesClusterAgentPool agentPoolProfile2 = kubernetesCluster.agentPools().get(agentPoolName2);
Assertions.assertEquals(0, agentPoolProfile2.nodeSize());
Assertions.assertEquals(10, agentPoolProfile2.maximumPodsPerNode());
kubernetesCluster.update()
.updateAgentPool(agentPoolName1)
.withoutAutoScaling()
.parent()
.apply();
kubernetesCluster.update()
.withoutAgentPool(agentPoolName1)
.withoutAgentPool(agentPoolName2)
.defineAgentPool(agentPoolName3)
.withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_A2_V2)
.withAgentPoolVirtualMachineCount(0)
.attach()
.apply();
Assertions.assertEquals(2, kubernetesCluster.agentPools().size());
KubernetesClusterAgentPool agentPoolProfile3 = kubernetesCluster.agentPools().get(agentPoolName3);
Assertions.assertEquals(0, agentPoolProfile3.nodeSize());
}
@Test
/**
* Parse azure auth to hashmap
*
* @param authFilename the azure auth location
* @return all fields in azure auth json
* @throws Exception exception
*/
private static HashMap<String, String> parseAuthFile(String authFilename) throws Exception {
String content = new String(Files.readAllBytes(new File(authFilename).toPath()), StandardCharsets.UTF_8).trim();
HashMap<String, String> auth = new HashMap<>();
if (isJsonBased(content)) {
auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON);
} else {
Properties authSettings = new Properties();
FileInputStream credentialsFileStream = new FileInputStream(new File(authFilename));
authSettings.load(credentialsFileStream);
credentialsFileStream.close();
for (final String authName : authSettings.stringPropertyNames()) {
auth.put(authName, authSettings.getProperty(authName));
}
}
return auth;
}
private static boolean isJsonBased(String content) {
return content.startsWith("{");
}
} |
We have stopped the autogenerated CommunicationErrorException from being exposed to the end users and instead created custom exceptions for each one of the different packages. Here's an example on how we did that for the Identity client: https://github.com/Azure/azure-sdk-for-java/blob/a466b3d474290eacdbd1a7afcf211d431df7356f/sdk/communication/azure-communication-identity/src/main/java/com/azure/communication/identity/CommunicationIdentityAsyncClient.java#L251 And here's how we did it on the Phone Numbers Client: https://github.com/Azure/azure-sdk-for-java/blob/a466b3d474290eacdbd1a7afcf211d431df7356f/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/PhoneNumbersAsyncClient.java#L230 In this case you don't have to translate it, but you will have to create a custom error exception for the Download Client as we did for the identity and phone numbers packages. | private Flux<ByteBuffer> getResponseBody(HttpResponse response) {
switch (response.getStatusCode()) {
case 200:
case 206:
return response.getBody();
default:
throw logger.logExceptionAsError(
new CommunicationErrorException(formatExceptionMessage(response), response)
);
}
} | new CommunicationErrorException(formatExceptionMessage(response), response) | private Flux<ByteBuffer> getResponseBody(HttpResponse response) {
switch (response.getStatusCode()) {
case 200:
case 206:
return response.getBody();
default:
throw logger.logExceptionAsError(
new CallingServerResponseException(formatExceptionMessage(response), response)
);
}
} | class ContentDownloader {
private final String resourceEndpoint;
private final HttpPipeline httpPipeline;
private final ClientLogger logger;
ContentDownloader(String resourceEndpoint, HttpPipeline httpPipeline,
ClientLogger logger) {
this.resourceEndpoint = resourceEndpoint;
this.httpPipeline = httpPipeline;
this.logger = logger;
}
Mono<Response<Void>> downloadToStream(OutputStream stream, URI endpoint,
ParallelDownloadOptions parallelDownloadOptions, Context context) {
return downloadTo(endpoint, parallelDownloadOptions, context,
chunkNum -> progressLock -> totalProgress -> response ->
writeBodyToStream(response, stream, chunkNum, parallelDownloadOptions,
progressLock, totalProgress).flux());
}
Mono<Response<Void>> downloadToFile(AsynchronousFileChannel file, URI endpoint,
ParallelDownloadOptions parallelDownloadOptions, Context context) {
return downloadTo(endpoint, parallelDownloadOptions, context,
chunkNum -> progressLock -> totalProgress -> response ->
writeBodyToFile(response, file, chunkNum, parallelDownloadOptions, progressLock, totalProgress).flux());
}
private Mono<Response<Void>> downloadTo(
URI endpoint,
ParallelDownloadOptions parallelDownloadOptions, Context context,
Function<Integer, Function<Lock, Function<AtomicLong, Function<Response<Flux<ByteBuffer>>, Flux<Void>>>>> writer) {
Lock progressLock = new ReentrantLock();
AtomicLong totalProgress = new AtomicLong(0);
Function<HttpRange, Mono<Response<Flux<ByteBuffer>>>> downloadFunc =
range -> downloadStreamingWithResponse(endpoint, range, context);
return downloadFirstChunk(parallelDownloadOptions, downloadFunc)
.flatMap(setupTuple2 -> {
long newCount = setupTuple2.getT1();
int numChunks = calculateNumBlocks(newCount, parallelDownloadOptions.getBlockSizeLong());
numChunks = numChunks == 0 ? 1 : numChunks;
Response<Flux<ByteBuffer>> initialResponse = setupTuple2.getT2();
return Flux.range(0, numChunks)
.flatMap(chunkNum -> downloadChunk(chunkNum, initialResponse,
parallelDownloadOptions, newCount, downloadFunc,
writer.apply(chunkNum).apply(progressLock).apply(totalProgress)))
.then(Mono.just(new SimpleResponse<>(initialResponse, null)));
});
}
Mono<Response<Flux<ByteBuffer>>> downloadStreamingWithResponse(URI endpoint, HttpRange httpRange, Context context) {
Mono<HttpResponse> httpResponse = makeDownloadRequest(endpoint, httpRange, context);
return httpResponse.map(response -> {
Flux<ByteBuffer> result = getFluxStream(response, endpoint, httpRange, context);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), result);
});
}
private Flux<ByteBuffer> getFluxStream(HttpResponse response, URI endpoint, HttpRange httpRange, Context context) {
return FluxUtil.createRetriableDownloadFlux(
() -> getResponseBody(response),
(Throwable throwable, Long aLong) -> {
HttpRange range;
if (httpRange != null) {
range = new HttpRange(aLong + 1, httpRange.getLength() - aLong - 1);
} else {
range = new HttpRange(aLong + 1);
}
Mono<HttpResponse> resumeResponse = makeDownloadRequest(endpoint, range, context);
return resumeResponse.map(this::getResponseBody).block();
},
Constants.ContentDownloader.MAX_RETRIES
);
}
private String formatExceptionMessage(HttpResponse httpResponse) {
return String.format("Service Request failed!%nStatus: %s", httpResponse.getStatusCode());
}
private Mono<HttpResponse> makeDownloadRequest(URI endpoint,
HttpRange httpRange,
Context context) {
HttpRequest request = getHttpRequest(endpoint, httpRange);
URL urlToSignWith = getUrlToSignRequestWith(endpoint);
Context finalContext;
if (context == null) {
finalContext = new Context("hmacSignatureURL", urlToSignWith);
} else {
finalContext = context.addData("hmacSignatureURL", urlToSignWith);
}
return httpPipeline.send(request, finalContext);
}
private URL getUrlToSignRequestWith(URI endpoint) {
try {
String path = endpoint.getPath();
if (path.startsWith("/")) {
path = path.substring(1);
}
return new URL(resourceEndpoint + path);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException(ex));
}
}
private HttpRequest getHttpRequest(URI endpoint, HttpRange httpRange) {
HttpRequest request = new HttpRequest(HttpMethod.GET, endpoint.toString());
if (null != httpRange) {
request.setHeader(Constants.HeaderNames.RANGE, httpRange.toString());
}
return request;
}
private Mono<Tuple2<Long, Response<Flux<ByteBuffer>>>> downloadFirstChunk(
ParallelDownloadOptions parallelDownloadOptions,
Function<HttpRange, Mono<Response<Flux<ByteBuffer>>>> downloader) {
return downloader.apply(new HttpRange(0, parallelDownloadOptions.getBlockSizeLong()))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(response -> {
long totalLength = extractTotalBlobLength(
response.getHeaders().getValue(Constants.HeaderNames.CONTENT_RANGE)
);
return Mono.zip(Mono.just(totalLength), Mono.just(response));
})
.onErrorResume(CommunicationErrorException.class, exception -> {
if (exception.getResponse().getStatusCode() == 416
&& extractTotalBlobLength(
exception.getResponse().getHeaderValue(Constants.HeaderNames.CONTENT_RANGE)) == 0) {
return downloader.apply(new HttpRange(0, 0L)).subscribeOn(Schedulers.boundedElastic())
.flatMap(response -> {
/*
Ensure the blob is still 0 length by checking our download was the full length.
(200 is for full blob; 206 is partial).
*/
if (response.getStatusCode() != 200) {
Mono.error(new IllegalStateException("Blob was modified mid download. It was "
+ "originally 0 bytes and is now larger."));
}
return Mono.zip(Mono.just(0L), Mono.just(response));
});
}
return Mono.error(exception);
});
}
private long extractTotalBlobLength(String contentRange) {
return contentRange == null ? 0 : Long.parseLong(contentRange.split("/")[1]);
}
private int calculateNumBlocks(long dataSize, long blockLength) {
int numBlocks = toIntExact(dataSize / blockLength);
if (dataSize % blockLength != 0) {
numBlocks++;
}
return numBlocks;
}
private <T> Flux<T> downloadChunk(Integer chunkNum, Response<Flux<ByteBuffer>> initialResponse,
ParallelDownloadOptions parallelDownloadOptions, long newCount,
Function<HttpRange, Mono<Response<Flux<ByteBuffer>>>> downloader,
Function<Response<Flux<ByteBuffer>>, Flux<T>> returnTransformer) {
if (chunkNum == 0) {
return returnTransformer.apply(initialResponse);
}
long modifier = chunkNum.longValue() * parallelDownloadOptions.getBlockSizeLong();
long chunkSizeActual = Math.min(parallelDownloadOptions.getBlockSizeLong(),
newCount - modifier);
HttpRange chunkRange = new HttpRange(modifier, chunkSizeActual);
return downloader.apply(chunkRange)
.subscribeOn(Schedulers.boundedElastic())
.flatMapMany(returnTransformer);
}
private static Mono<Void> writeBodyToFile(Response<Flux<ByteBuffer>> response, AsynchronousFileChannel file,
long chunkNum, ParallelDownloadOptions parallelDownloadOptions,
Lock progressLock,
AtomicLong totalProgress) {
Flux<ByteBuffer> data = response.getValue();
data = ProgressReporter.addParallelProgressReporting(data,
parallelDownloadOptions.getProgressReceiver(), progressLock,
totalProgress);
return FluxUtil.writeFile(data, file, chunkNum * parallelDownloadOptions.getBlockSizeLong());
}
private static Mono<Void> writeBodyToStream(Response<Flux<ByteBuffer>> response, OutputStream stream,
long chunkNum, ParallelDownloadOptions parallelDownloadOptions,
Lock progressLock, AtomicLong totalProgress) {
Flux<ByteBuffer> data = response.getValue();
Flux<ByteBuffer> finalData = ProgressReporter.addParallelProgressReporting(data,
parallelDownloadOptions.getProgressReceiver(), progressLock,
totalProgress);
return Mono.create(emitter -> {
finalData.doOnError(emitter::error).subscribe(byteBuffer -> {
try {
byte[] bytes = byteBuffer.array();
stream.write(bytes, (int) ((int) chunkNum * parallelDownloadOptions.getBlockSizeLong()), bytes.length);
emitter.success();
} catch (IOException ex) {
emitter.error(ex);
}
});
}
);
}
void downloadToFileCleanup(AsynchronousFileChannel channel, Path filePath, SignalType signalType) {
try {
channel.close();
if (!signalType.equals(SignalType.ON_COMPLETE)) {
Files.deleteIfExists(filePath);
logger.verbose("Downloading to file failed. Cleaning up resources.");
}
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
} | class ContentDownloader {
private final String resourceEndpoint;
private final HttpPipeline httpPipeline;
private final ClientLogger logger;
ContentDownloader(String resourceEndpoint, HttpPipeline httpPipeline,
ClientLogger logger) {
this.resourceEndpoint = resourceEndpoint;
this.httpPipeline = httpPipeline;
this.logger = logger;
}
Mono<Response<Void>> downloadToStream(String sourceEndpoint, OutputStream destinationStream,
ParallelDownloadOptions parallelDownloadOptions, Context context) {
return downloadTo(sourceEndpoint, parallelDownloadOptions, context,
chunkNum -> totalProgress -> response ->
writeBodyToStream(response, destinationStream, chunkNum, parallelDownloadOptions, totalProgress).flux());
}
Mono<Response<Void>> downloadToFile(String sourceEndpoint, AsynchronousFileChannel destinationFile,
ParallelDownloadOptions parallelDownloadOptions, Context context) {
return downloadTo(sourceEndpoint, parallelDownloadOptions, context,
chunkNum -> totalProgress -> response ->
writeBodyToFile(response, destinationFile, chunkNum, parallelDownloadOptions, totalProgress).flux());
}
private Mono<Response<Void>> downloadTo(
String endpoint,
ParallelDownloadOptions parallelDownloadOptions, Context context,
Function<Integer, Function<AtomicLong, Function<Response<Flux<ByteBuffer>>, Flux<Void>>>> writer) {
AtomicLong totalProgress = new AtomicLong(0);
Function<HttpRange, Mono<Response<Flux<ByteBuffer>>>> downloadFunc =
range -> downloadStreamWithResponse(endpoint, range, context);
return downloadFirstChunk(parallelDownloadOptions, downloadFunc)
.flatMap(setupTuple2 -> {
long newCount = setupTuple2.getT1();
int numChunks = calculateNumBlocks(newCount, parallelDownloadOptions.getBlockSizeLong());
numChunks = numChunks == 0 ? 1 : numChunks;
Response<Flux<ByteBuffer>> initialResponse = setupTuple2.getT2();
return Flux.range(0, numChunks)
.flatMap(chunkNum -> downloadChunk(chunkNum, initialResponse,
parallelDownloadOptions, newCount, downloadFunc,
writer.apply(chunkNum).apply(totalProgress)))
.then(Mono.just(new SimpleResponse<>(initialResponse, null)));
});
}
Flux<ByteBuffer> downloadStream(String sourceEndpoint, HttpRange httpRange) {
Mono<HttpResponse> httpResponse = makeDownloadRequest(sourceEndpoint, httpRange, null);
return httpResponse
.map(response -> getFluxStream(response, sourceEndpoint, httpRange, null))
.flux()
.flatMap(flux -> flux);
}
Mono<Response<Flux<ByteBuffer>>> downloadStreamWithResponse(String endpoint, HttpRange httpRange) {
return downloadStreamWithResponse(endpoint, httpRange, null);
}
Mono<Response<Flux<ByteBuffer>>> downloadStreamWithResponse(String sourceEndpoint, HttpRange httpRange,
Context context) {
Mono<HttpResponse> httpResponse = makeDownloadRequest(sourceEndpoint, httpRange, context);
return httpResponse.map(response -> {
Flux<ByteBuffer> result = getFluxStream(response, sourceEndpoint, httpRange, context);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), result);
});
}
private Flux<ByteBuffer> getFluxStream(HttpResponse httpResponse, String sourceEndpoint, HttpRange httpRange,
Context context) {
return FluxUtil.createRetriableDownloadFlux(
() -> getResponseBody(httpResponse),
(Throwable throwable, Long aLong) -> {
HttpRange range;
if (httpRange != null) {
range = new HttpRange(aLong + 1, httpRange.getLength() - aLong - 1);
} else {
range = new HttpRange(aLong + 1);
}
Mono<HttpResponse> resumeResponse = makeDownloadRequest(sourceEndpoint, range, context);
return resumeResponse.map(this::getResponseBody).block();
},
Constants.ContentDownloader.MAX_RETRIES
);
}
private String formatExceptionMessage(HttpResponse httpResponse) {
return String.format("Service Request failed!%nStatus: %s", httpResponse.getStatusCode());
}
private Mono<HttpResponse> makeDownloadRequest(String sourceEndpoint,
HttpRange httpRange,
Context context) {
HttpRequest request = getHttpRequest(sourceEndpoint, httpRange);
URL urlToSignWith = getUrlToSignRequestWith(sourceEndpoint);
Context finalContext;
if (context == null) {
finalContext = new Context("hmacSignatureURL", urlToSignWith);
} else {
finalContext = context.addData("hmacSignatureURL", urlToSignWith);
}
return httpPipeline.send(request, finalContext);
}
private URL getUrlToSignRequestWith(String endpoint) {
try {
String path = new URL(endpoint).getPath();
if (path.startsWith("/")) {
path = path.substring(1);
}
return new URL(resourceEndpoint + path);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(new IllegalArgumentException(ex));
}
}
private HttpRequest getHttpRequest(String sourceEndpoint, HttpRange httpRange) {
HttpRequest request = new HttpRequest(HttpMethod.GET, sourceEndpoint);
if (null != httpRange) {
request.setHeader(Constants.HeaderNames.RANGE, httpRange.toString());
}
return request;
}
private Mono<Tuple2<Long, Response<Flux<ByteBuffer>>>> downloadFirstChunk(
ParallelDownloadOptions parallelDownloadOptions,
Function<HttpRange, Mono<Response<Flux<ByteBuffer>>>> downloader) {
return downloader.apply(new HttpRange(0, parallelDownloadOptions.getBlockSizeLong()))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(response -> {
long totalLength = extractTotalBlobLength(
response.getHeaders().getValue(Constants.HeaderNames.CONTENT_RANGE)
);
return Mono.zip(Mono.just(totalLength), Mono.just(response));
})
.onErrorResume(CallingServerResponseException.class, exception -> {
if (exception.getResponse().getStatusCode() == 416
&& extractTotalBlobLength(
exception.getResponse().getHeaderValue(Constants.HeaderNames.CONTENT_RANGE)) == 0) {
return downloader.apply(new HttpRange(0, 0L)).subscribeOn(Schedulers.boundedElastic())
.flatMap(response -> {
/*
Ensure the blob is still 0 length by checking our download was the full length.
(200 is for full blob; 206 is partial).
*/
if (response.getStatusCode() != 200) {
Mono.error(new IllegalStateException("Blob was modified mid download. It was "
+ "originally 0 bytes and is now larger."));
}
return Mono.zip(Mono.just(0L), Mono.just(response));
});
}
return Mono.error(exception);
});
}
private long extractTotalBlobLength(String contentRange) {
return contentRange == null ? 0 : Long.parseLong(contentRange.split("/")[1]);
}
private int calculateNumBlocks(long dataSize, long blockLength) {
int numBlocks = toIntExact(dataSize / blockLength);
if (dataSize % blockLength != 0) {
numBlocks++;
}
return numBlocks;
}
private <T> Flux<T> downloadChunk(Integer chunkNum, Response<Flux<ByteBuffer>> initialResponse,
ParallelDownloadOptions parallelDownloadOptions, long newCount,
Function<HttpRange, Mono<Response<Flux<ByteBuffer>>>> downloader,
Function<Response<Flux<ByteBuffer>>, Flux<T>> returnTransformer) {
if (chunkNum == 0) {
return returnTransformer.apply(initialResponse);
}
long modifier = chunkNum.longValue() * parallelDownloadOptions.getBlockSizeLong();
long chunkSizeActual = Math.min(parallelDownloadOptions.getBlockSizeLong(),
newCount - modifier);
HttpRange chunkRange = new HttpRange(modifier, chunkSizeActual);
return downloader.apply(chunkRange)
.subscribeOn(Schedulers.boundedElastic())
.flatMapMany(returnTransformer);
}
private static Mono<Void> writeBodyToFile(Response<Flux<ByteBuffer>> response, AsynchronousFileChannel file,
long chunkNum, ParallelDownloadOptions parallelDownloadOptions,
AtomicLong totalProgress) {
Flux<ByteBuffer> data = response.getValue();
data = ProgressReporter.addParallelProgressReporting(data,
parallelDownloadOptions.getProgressReceiver(), totalProgress);
return FluxUtil.writeFile(data, file, chunkNum * parallelDownloadOptions.getBlockSizeLong());
}
private static Mono<Void> writeBodyToStream(Response<Flux<ByteBuffer>> response, OutputStream stream,
long chunkNum, ParallelDownloadOptions parallelDownloadOptions,
AtomicLong totalProgress) {
Flux<ByteBuffer> data = response.getValue();
Flux<ByteBuffer> finalData = ProgressReporter.addParallelProgressReporting(data,
parallelDownloadOptions.getProgressReceiver(), totalProgress);
return Mono.create(emitter -> finalData.doOnError(emitter::error).subscribe(byteBuffer -> {
try {
byte[] bytes = byteBuffer.array();
stream.write(bytes, (int) ((int) chunkNum * parallelDownloadOptions.getBlockSizeLong()), bytes.length);
emitter.success();
} catch (IOException ex) {
emitter.error(ex);
}
})
);
}
void downloadToFileCleanup(AsynchronousFileChannel channel, Path filePath, SignalType signalType) {
try {
channel.close();
if (!signalType.equals(SignalType.ON_COMPLETE)) {
Files.deleteIfExists(filePath);
logger.verbose("Downloading to file failed. Cleaning up resources.");
}
} catch (IOException e) {
throw logger.logExceptionAsError(new UncheckedIOException(e));
}
}
} |
Is it possible to add a test for this? | public Mono<Void> updateDisposition(String lockToken, DeliveryState deliveryState) {
if (isDisposed()) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition on closed processor.", lockToken, deliveryState)));
}
final ServiceBusReceiveLink link = currentLink;
if (link == null) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition with no link.", lockToken, deliveryState)));
}
return link.updateDisposition(lockToken, deliveryState).onErrorResume(error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (AmqpErrorCondition.TIMEOUT_ERROR.equals(amqpException.getErrorCondition())) {
return link.closeAsync().then(Mono.error(error));
}
}
return Mono.error(error);
});
} | return link.updateDisposition(lockToken, deliveryState).onErrorResume(error -> { | public Mono<Void> updateDisposition(String lockToken, DeliveryState deliveryState) {
if (isDisposed()) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition on closed processor.", lockToken, deliveryState)));
}
final ServiceBusReceiveLink link = currentLink;
if (link == null) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition with no link.", lockToken, deliveryState)));
}
return link.updateDisposition(lockToken, deliveryState).onErrorResume(error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (AmqpErrorCondition.TIMEOUT_ERROR.equals(amqpException.getErrorCondition())) {
return link.closeAsync().then(Mono.error(error));
}
}
return Mono.error(error);
});
} | class ServiceBusReceiveLinkProcessor extends FluxProcessor<ServiceBusReceiveLink, Message>
implements Subscription {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiveLinkProcessor.class);
private final Object lock = new Object();
private final Object queueLock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final AtomicReference<String> linkName = new AtomicReference<>();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicInteger pendingMessages = new AtomicInteger();
private final int minimumNumberOfMessages;
private final int prefetch;
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final AmqpRetryPolicy retryPolicy;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile ServiceBusReceiveLink currentLink;
private volatile Disposable currentLinkSubscriptions;
private volatile Disposable retrySubscription;
private volatile long requested;
private static final AtomicLongFieldUpdater<ServiceBusReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<ServiceBusReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* Creates an instance of {@link ServiceBusReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param retryPolicy Retry policy to apply when fetching a new AMQP channel.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public ServiceBusReceiveLinkProcessor(int prefetch, AmqpRetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.minimumNumberOfMessages = Math.floorDiv(prefetch, 3);
}
public String getLinkName() {
return linkName.get();
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(ServiceBusReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
final String entityPath = next.getEntityPath();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
next.setEmptyCreditListener(() -> 0);
currentLinkSubscriptions = Disposables.composite(
next.receive().publishOn(Schedulers.boundedElastic()).subscribe(message -> {
synchronized (queueLock) {
messageQueue.add(message);
pendingMessages.incrementAndGet();
}
drain();
}),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
retryAttempts.set(0);
}
},
error -> {
currentLink = null;
onError(error);
},
() -> {
if (isTerminated()) {
logger.info("Processor is terminated. Disposing of link processor.");
dispose();
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream has completed. Disposing of link processor.");
dispose();
} else {
logger.info("Receive link endpoint states are closed. Requesting another.");
final AmqpReceiveLink existing = currentLink;
currentLink = null;
disposeReceiver(existing);
requestUpstream();
}
}));
}
checkAndAddCredits(next);
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.", linkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
if (isTerminated()) {
logger.info("AmqpReceiveLinkProcessor is terminated. Not reopening on error.");
return;
}
final int attempt = retryAttempts.incrementAndGet();
final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt);
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
if (retryInterval != null && upstream != Operators.cancelledSubscription()) {
logger.warning("linkName[{}] entityPath[{}]. Transient error occurred. Attempt: {}. Retrying after {} ms.",
linkName, entityPath, attempt, retryInterval.toMillis(), throwable);
retrySubscription = Mono.delay(retryInterval).subscribe(i -> requestUpstream());
return;
}
logger.warning("linkName[{}] entityPath[{}]. Non-retryable error occurred in AMQP receive link.",
linkName, entityPath, throwable);
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
drain();
onDispose();
}
/**
* When upstream has completed emitting messages.
*/
@Override
public void onComplete() {
this.upstream = Operators.cancelledSubscription();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
final AmqpReceiveLink link = currentLink;
if (link == null) {
return;
}
checkAndAddCredits(link);
drain();
}
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (upstream == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
upstream.request(1L);
}
private void onDispose() {
if (retrySubscription != null && !retrySubscription.isDisposed()) {
retrySubscription.dispose();
}
disposeReceiver(currentLink);
currentLink = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = requested;
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
final Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
synchronized (queueLock) {
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
pendingMessages.set(0);
}
return;
}
try {
subscriber.onNext(message);
pendingMessages.decrementAndGet();
if (prefetch > 0) {
checkAndAddCredits(currentLink);
}
} catch (Exception e) {
logger.error("Exception occurred while handling downstream onNext operation.", e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
if (requested != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
synchronized (queueLock) {
messageQueue.clear();
pendingMessages.set(0);
}
return true;
}
private void checkAndAddCredits(AmqpReceiveLink link) {
if (link == null) {
return;
}
synchronized (lock) {
final int linkCredits = link.getCredits();
final int credits = getCreditsToAdd(linkCredits);
logger.info("Link credits='{}', Link credits to add: '{}'", linkCredits, credits);
if (credits > 0) {
link.addCredits(credits).subscribe();
}
}
}
private int getCreditsToAdd(int linkCredits) {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long r = requested;
final boolean hasBackpressure = r != Long.MAX_VALUE;
if (subscriber == null || r == 0) {
logger.info("Not adding credits. No downstream subscribers or items requested.");
return 0;
}
final int creditsToAdd;
final int expectedTotalCredit;
if (prefetch == 0) {
if (r <= Integer.MAX_VALUE) {
expectedTotalCredit = (int) r;
} else {
expectedTotalCredit = Integer.MAX_VALUE;
}
} else {
expectedTotalCredit = prefetch;
}
logger.info("linkCredits: '{}', expectedTotalCredit: '{}'", linkCredits, expectedTotalCredit);
synchronized (queueLock) {
final int queuedMessages = pendingMessages.get();
final int pending = queuedMessages + linkCredits;
if (hasBackpressure) {
creditsToAdd = Math.max(expectedTotalCredit - pending, 0);
} else {
creditsToAdd = minimumNumberOfMessages >= queuedMessages
? Math.max(expectedTotalCredit - pending, 0)
: 0;
}
logger.info("prefetch: '{}', requested: '{}', linkCredits: '{}', expectedTotalCredit: '{}', queuedMessages:"
+ "'{}', creditsToAdd: '{}', messageQueue.size(): '{}'", getPrefetch(), r, linkCredits,
expectedTotalCredit, queuedMessages, creditsToAdd, messageQueue.size());
}
return creditsToAdd;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncCloseable) {
((AsyncCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} | class ServiceBusReceiveLinkProcessor extends FluxProcessor<ServiceBusReceiveLink, Message>
implements Subscription {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiveLinkProcessor.class);
private final Object lock = new Object();
private final Object queueLock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final AtomicReference<String> linkName = new AtomicReference<>();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicInteger pendingMessages = new AtomicInteger();
private final int minimumNumberOfMessages;
private final int prefetch;
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final AmqpRetryPolicy retryPolicy;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile ServiceBusReceiveLink currentLink;
private volatile Disposable currentLinkSubscriptions;
private volatile Disposable retrySubscription;
private volatile long requested;
private static final AtomicLongFieldUpdater<ServiceBusReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<ServiceBusReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* Creates an instance of {@link ServiceBusReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param retryPolicy Retry policy to apply when fetching a new AMQP channel.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public ServiceBusReceiveLinkProcessor(int prefetch, AmqpRetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.minimumNumberOfMessages = Math.floorDiv(prefetch, 3);
}
public String getLinkName() {
return linkName.get();
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(ServiceBusReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
final String entityPath = next.getEntityPath();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
next.setEmptyCreditListener(() -> 0);
currentLinkSubscriptions = Disposables.composite(
next.receive().publishOn(Schedulers.boundedElastic()).subscribe(message -> {
synchronized (queueLock) {
messageQueue.add(message);
pendingMessages.incrementAndGet();
}
drain();
}),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
retryAttempts.set(0);
}
},
error -> {
currentLink = null;
onError(error);
},
() -> {
if (isTerminated()) {
logger.info("Processor is terminated. Disposing of link processor.");
dispose();
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream has completed. Disposing of link processor.");
dispose();
} else {
logger.info("Receive link endpoint states are closed. Requesting another.");
final AmqpReceiveLink existing = currentLink;
currentLink = null;
disposeReceiver(existing);
requestUpstream();
}
}));
}
checkAndAddCredits(next);
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.", linkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
if (isTerminated()) {
logger.info("AmqpReceiveLinkProcessor is terminated. Not reopening on error.");
return;
}
final int attempt = retryAttempts.incrementAndGet();
final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt);
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
if (retryInterval != null && upstream != Operators.cancelledSubscription()) {
logger.warning("linkName[{}] entityPath[{}]. Transient error occurred. Attempt: {}. Retrying after {} ms.",
linkName, entityPath, attempt, retryInterval.toMillis(), throwable);
retrySubscription = Mono.delay(retryInterval).subscribe(i -> requestUpstream());
return;
}
logger.warning("linkName[{}] entityPath[{}]. Non-retryable error occurred in AMQP receive link.",
linkName, entityPath, throwable);
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
drain();
onDispose();
}
/**
* When upstream has completed emitting messages.
*/
@Override
public void onComplete() {
this.upstream = Operators.cancelledSubscription();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
final AmqpReceiveLink link = currentLink;
if (link == null) {
return;
}
checkAndAddCredits(link);
drain();
}
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (upstream == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
upstream.request(1L);
}
private void onDispose() {
if (retrySubscription != null && !retrySubscription.isDisposed()) {
retrySubscription.dispose();
}
disposeReceiver(currentLink);
currentLink = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = requested;
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
final Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
synchronized (queueLock) {
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
pendingMessages.set(0);
}
return;
}
try {
subscriber.onNext(message);
pendingMessages.decrementAndGet();
if (prefetch > 0) {
checkAndAddCredits(currentLink);
}
} catch (Exception e) {
logger.error("Exception occurred while handling downstream onNext operation.", e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
if (requested != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
synchronized (queueLock) {
messageQueue.clear();
pendingMessages.set(0);
}
return true;
}
private void checkAndAddCredits(AmqpReceiveLink link) {
if (link == null) {
return;
}
synchronized (lock) {
final int linkCredits = link.getCredits();
final int credits = getCreditsToAdd(linkCredits);
logger.info("Link credits='{}', Link credits to add: '{}'", linkCredits, credits);
if (credits > 0) {
link.addCredits(credits).subscribe();
}
}
}
private int getCreditsToAdd(int linkCredits) {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long r = requested;
final boolean hasBackpressure = r != Long.MAX_VALUE;
if (subscriber == null || r == 0) {
logger.info("Not adding credits. No downstream subscribers or items requested.");
return 0;
}
final int creditsToAdd;
final int expectedTotalCredit;
if (prefetch == 0) {
if (r <= Integer.MAX_VALUE) {
expectedTotalCredit = (int) r;
} else {
expectedTotalCredit = Integer.MAX_VALUE;
}
} else {
expectedTotalCredit = prefetch;
}
logger.info("linkCredits: '{}', expectedTotalCredit: '{}'", linkCredits, expectedTotalCredit);
synchronized (queueLock) {
final int queuedMessages = pendingMessages.get();
final int pending = queuedMessages + linkCredits;
if (hasBackpressure) {
creditsToAdd = Math.max(expectedTotalCredit - pending, 0);
} else {
creditsToAdd = minimumNumberOfMessages >= queuedMessages
? Math.max(expectedTotalCredit - pending, 0)
: 0;
}
logger.info("prefetch: '{}', requested: '{}', linkCredits: '{}', expectedTotalCredit: '{}', queuedMessages:"
+ "'{}', creditsToAdd: '{}', messageQueue.size(): '{}'", getPrefetch(), r, linkCredits,
expectedTotalCredit, queuedMessages, creditsToAdd, messageQueue.size());
}
return creditsToAdd;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncCloseable) {
((AsyncCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} |
Created issue #22065 to followup | public Mono<Void> updateDisposition(String lockToken, DeliveryState deliveryState) {
if (isDisposed()) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition on closed processor.", lockToken, deliveryState)));
}
final ServiceBusReceiveLink link = currentLink;
if (link == null) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition with no link.", lockToken, deliveryState)));
}
return link.updateDisposition(lockToken, deliveryState).onErrorResume(error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (AmqpErrorCondition.TIMEOUT_ERROR.equals(amqpException.getErrorCondition())) {
return link.closeAsync().then(Mono.error(error));
}
}
return Mono.error(error);
});
} | return link.updateDisposition(lockToken, deliveryState).onErrorResume(error -> { | public Mono<Void> updateDisposition(String lockToken, DeliveryState deliveryState) {
if (isDisposed()) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition on closed processor.", lockToken, deliveryState)));
}
final ServiceBusReceiveLink link = currentLink;
if (link == null) {
return monoError(logger, new IllegalStateException(String.format(
"lockToken[%s]. state[%s]. Cannot update disposition with no link.", lockToken, deliveryState)));
}
return link.updateDisposition(lockToken, deliveryState).onErrorResume(error -> {
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
if (AmqpErrorCondition.TIMEOUT_ERROR.equals(amqpException.getErrorCondition())) {
return link.closeAsync().then(Mono.error(error));
}
}
return Mono.error(error);
});
} | class ServiceBusReceiveLinkProcessor extends FluxProcessor<ServiceBusReceiveLink, Message>
implements Subscription {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiveLinkProcessor.class);
private final Object lock = new Object();
private final Object queueLock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final AtomicReference<String> linkName = new AtomicReference<>();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicInteger pendingMessages = new AtomicInteger();
private final int minimumNumberOfMessages;
private final int prefetch;
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final AmqpRetryPolicy retryPolicy;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile ServiceBusReceiveLink currentLink;
private volatile Disposable currentLinkSubscriptions;
private volatile Disposable retrySubscription;
private volatile long requested;
private static final AtomicLongFieldUpdater<ServiceBusReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<ServiceBusReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* Creates an instance of {@link ServiceBusReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param retryPolicy Retry policy to apply when fetching a new AMQP channel.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public ServiceBusReceiveLinkProcessor(int prefetch, AmqpRetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.minimumNumberOfMessages = Math.floorDiv(prefetch, 3);
}
public String getLinkName() {
return linkName.get();
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(ServiceBusReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
final String entityPath = next.getEntityPath();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
next.setEmptyCreditListener(() -> 0);
currentLinkSubscriptions = Disposables.composite(
next.receive().publishOn(Schedulers.boundedElastic()).subscribe(message -> {
synchronized (queueLock) {
messageQueue.add(message);
pendingMessages.incrementAndGet();
}
drain();
}),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
retryAttempts.set(0);
}
},
error -> {
currentLink = null;
onError(error);
},
() -> {
if (isTerminated()) {
logger.info("Processor is terminated. Disposing of link processor.");
dispose();
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream has completed. Disposing of link processor.");
dispose();
} else {
logger.info("Receive link endpoint states are closed. Requesting another.");
final AmqpReceiveLink existing = currentLink;
currentLink = null;
disposeReceiver(existing);
requestUpstream();
}
}));
}
checkAndAddCredits(next);
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.", linkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
if (isTerminated()) {
logger.info("AmqpReceiveLinkProcessor is terminated. Not reopening on error.");
return;
}
final int attempt = retryAttempts.incrementAndGet();
final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt);
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
if (retryInterval != null && upstream != Operators.cancelledSubscription()) {
logger.warning("linkName[{}] entityPath[{}]. Transient error occurred. Attempt: {}. Retrying after {} ms.",
linkName, entityPath, attempt, retryInterval.toMillis(), throwable);
retrySubscription = Mono.delay(retryInterval).subscribe(i -> requestUpstream());
return;
}
logger.warning("linkName[{}] entityPath[{}]. Non-retryable error occurred in AMQP receive link.",
linkName, entityPath, throwable);
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
drain();
onDispose();
}
/**
* When upstream has completed emitting messages.
*/
@Override
public void onComplete() {
this.upstream = Operators.cancelledSubscription();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
final AmqpReceiveLink link = currentLink;
if (link == null) {
return;
}
checkAndAddCredits(link);
drain();
}
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (upstream == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
upstream.request(1L);
}
private void onDispose() {
if (retrySubscription != null && !retrySubscription.isDisposed()) {
retrySubscription.dispose();
}
disposeReceiver(currentLink);
currentLink = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = requested;
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
final Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
synchronized (queueLock) {
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
pendingMessages.set(0);
}
return;
}
try {
subscriber.onNext(message);
pendingMessages.decrementAndGet();
if (prefetch > 0) {
checkAndAddCredits(currentLink);
}
} catch (Exception e) {
logger.error("Exception occurred while handling downstream onNext operation.", e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
if (requested != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
synchronized (queueLock) {
messageQueue.clear();
pendingMessages.set(0);
}
return true;
}
private void checkAndAddCredits(AmqpReceiveLink link) {
if (link == null) {
return;
}
synchronized (lock) {
final int linkCredits = link.getCredits();
final int credits = getCreditsToAdd(linkCredits);
logger.info("Link credits='{}', Link credits to add: '{}'", linkCredits, credits);
if (credits > 0) {
link.addCredits(credits).subscribe();
}
}
}
private int getCreditsToAdd(int linkCredits) {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long r = requested;
final boolean hasBackpressure = r != Long.MAX_VALUE;
if (subscriber == null || r == 0) {
logger.info("Not adding credits. No downstream subscribers or items requested.");
return 0;
}
final int creditsToAdd;
final int expectedTotalCredit;
if (prefetch == 0) {
if (r <= Integer.MAX_VALUE) {
expectedTotalCredit = (int) r;
} else {
expectedTotalCredit = Integer.MAX_VALUE;
}
} else {
expectedTotalCredit = prefetch;
}
logger.info("linkCredits: '{}', expectedTotalCredit: '{}'", linkCredits, expectedTotalCredit);
synchronized (queueLock) {
final int queuedMessages = pendingMessages.get();
final int pending = queuedMessages + linkCredits;
if (hasBackpressure) {
creditsToAdd = Math.max(expectedTotalCredit - pending, 0);
} else {
creditsToAdd = minimumNumberOfMessages >= queuedMessages
? Math.max(expectedTotalCredit - pending, 0)
: 0;
}
logger.info("prefetch: '{}', requested: '{}', linkCredits: '{}', expectedTotalCredit: '{}', queuedMessages:"
+ "'{}', creditsToAdd: '{}', messageQueue.size(): '{}'", getPrefetch(), r, linkCredits,
expectedTotalCredit, queuedMessages, creditsToAdd, messageQueue.size());
}
return creditsToAdd;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncCloseable) {
((AsyncCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} | class ServiceBusReceiveLinkProcessor extends FluxProcessor<ServiceBusReceiveLink, Message>
implements Subscription {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiveLinkProcessor.class);
private final Object lock = new Object();
private final Object queueLock = new Object();
private final AtomicBoolean isTerminated = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
private final AtomicReference<String> linkName = new AtomicReference<>();
private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>();
private final AtomicInteger pendingMessages = new AtomicInteger();
private final int minimumNumberOfMessages;
private final int prefetch;
private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>();
private final AtomicInteger wip = new AtomicInteger();
private final AmqpRetryPolicy retryPolicy;
private volatile Throwable lastError;
private volatile boolean isCancelled;
private volatile ServiceBusReceiveLink currentLink;
private volatile Disposable currentLinkSubscriptions;
private volatile Disposable retrySubscription;
private volatile long requested;
private static final AtomicLongFieldUpdater<ServiceBusReceiveLinkProcessor> REQUESTED =
AtomicLongFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, "requested");
private volatile Subscription upstream;
private static final AtomicReferenceFieldUpdater<ServiceBusReceiveLinkProcessor, Subscription> UPSTREAM =
AtomicReferenceFieldUpdater.newUpdater(ServiceBusReceiveLinkProcessor.class, Subscription.class,
"upstream");
/**
* Creates an instance of {@link ServiceBusReceiveLinkProcessor}.
*
* @param prefetch The number if messages to initially fetch.
* @param retryPolicy Retry policy to apply when fetching a new AMQP channel.
*
* @throws NullPointerException if {@code retryPolicy} is null.
* @throws IllegalArgumentException if {@code prefetch} is less than 0.
*/
public ServiceBusReceiveLinkProcessor(int prefetch, AmqpRetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
if (prefetch < 0) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'prefetch' cannot be less than 0."));
}
this.prefetch = prefetch;
this.minimumNumberOfMessages = Math.floorDiv(prefetch, 3);
}
public String getLinkName() {
return linkName.get();
}
/**
* Gets the error associated with this processor.
*
* @return Error associated with this processor. {@code null} if there is no error.
*/
@Override
public Throwable getError() {
return lastError;
}
/**
* Gets whether or not the processor is terminated.
*
* @return {@code true} if the processor has terminated; false otherwise.
*/
@Override
public boolean isTerminated() {
return isTerminated.get() || isCancelled;
}
@Override
public int getPrefetch() {
return prefetch;
}
/**
* When a subscription is obtained from upstream publisher.
*
* @param subscription Subscription to upstream publisher.
*/
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null");
if (!Operators.setOnce(UPSTREAM, this, subscription)) {
throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice."));
}
requestUpstream();
}
/**
* When the next AMQP link is fetched.
*
* @param next The next AMQP receive link.
*/
@Override
public void onNext(ServiceBusReceiveLink next) {
Objects.requireNonNull(next, "'next' cannot be null.");
if (isTerminated()) {
logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.",
next.getLinkName(), next.getEntityPath());
Operators.onNextDropped(next, currentContext());
return;
}
final String linkName = next.getLinkName();
final String entityPath = next.getEntityPath();
logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath);
final AmqpReceiveLink oldChannel;
final Disposable oldSubscription;
synchronized (lock) {
oldChannel = currentLink;
oldSubscription = currentLinkSubscriptions;
currentLink = next;
next.setEmptyCreditListener(() -> 0);
currentLinkSubscriptions = Disposables.composite(
next.receive().publishOn(Schedulers.boundedElastic()).subscribe(message -> {
synchronized (queueLock) {
messageQueue.add(message);
pendingMessages.incrementAndGet();
}
drain();
}),
next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe(
state -> {
if (state == AmqpEndpointState.ACTIVE) {
retryAttempts.set(0);
}
},
error -> {
currentLink = null;
onError(error);
},
() -> {
if (isTerminated()) {
logger.info("Processor is terminated. Disposing of link processor.");
dispose();
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream has completed. Disposing of link processor.");
dispose();
} else {
logger.info("Receive link endpoint states are closed. Requesting another.");
final AmqpReceiveLink existing = currentLink;
currentLink = null;
disposeReceiver(existing);
requestUpstream();
}
}));
}
checkAndAddCredits(next);
disposeReceiver(oldChannel);
if (oldSubscription != null) {
oldSubscription.dispose();
}
}
/**
* Sets up the downstream subscriber.
*
* @param actual The downstream subscriber.
*
* @throws IllegalStateException if there is already a downstream subscriber.
*/
@Override
public void subscribe(CoreSubscriber<? super Message> actual) {
Objects.requireNonNull(actual, "'actual' cannot be null.");
final boolean terminateSubscriber = isTerminated()
|| (currentLink == null && upstream == Operators.cancelledSubscription());
if (isTerminated()) {
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.", linkName, entityPath);
} else if (currentLink == null && upstream == Operators.cancelledSubscription()) {
logger.info("There is no current link and upstream is terminated.");
}
if (terminateSubscriber) {
actual.onSubscribe(Operators.emptySubscription());
if (hasError()) {
actual.onError(lastError);
} else {
actual.onComplete();
}
return;
}
if (downstream.compareAndSet(null, actual)) {
actual.onSubscribe(this);
drain();
} else {
Operators.error(actual, logger.logExceptionAsError(new IllegalStateException(
"There is already one downstream subscriber.'")));
}
}
/**
* When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP
* element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes.
*
* @param throwable Error that occurred in upstream publisher.
*/
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable, "'throwable' is required.");
if (isTerminated()) {
logger.info("AmqpReceiveLinkProcessor is terminated. Not reopening on error.");
return;
}
final int attempt = retryAttempts.incrementAndGet();
final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt);
final AmqpReceiveLink link = currentLink;
final String linkName = link != null ? link.getLinkName() : "n/a";
final String entityPath = link != null ? link.getEntityPath() : "n/a";
if (retryInterval != null && upstream != Operators.cancelledSubscription()) {
logger.warning("linkName[{}] entityPath[{}]. Transient error occurred. Attempt: {}. Retrying after {} ms.",
linkName, entityPath, attempt, retryInterval.toMillis(), throwable);
retrySubscription = Mono.delay(retryInterval).subscribe(i -> requestUpstream());
return;
}
logger.warning("linkName[{}] entityPath[{}]. Non-retryable error occurred in AMQP receive link.",
linkName, entityPath, throwable);
lastError = throwable;
isTerminated.set(true);
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber != null) {
subscriber.onError(throwable);
}
onDispose();
}
@Override
public void dispose() {
if (isTerminated.getAndSet(true)) {
return;
}
drain();
onDispose();
}
/**
* When upstream has completed emitting messages.
*/
@Override
public void onComplete() {
this.upstream = Operators.cancelledSubscription();
}
/**
* When downstream subscriber makes a back-pressure request.
*/
@Override
public void request(long request) {
if (!Operators.validate(request)) {
logger.warning("Invalid request: {}", request);
return;
}
Operators.addCap(REQUESTED, this, request);
final AmqpReceiveLink link = currentLink;
if (link == null) {
return;
}
checkAndAddCredits(link);
drain();
}
/**
* When downstream subscriber cancels their subscription.
*/
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
drain();
}
/**
* Requests another receive link from upstream.
*/
private void requestUpstream() {
if (isTerminated()) {
logger.info("Processor is terminated. Not requesting another link.");
return;
} else if (upstream == null) {
logger.info("There is no upstream. Not requesting another link.");
return;
} else if (upstream == Operators.cancelledSubscription()) {
logger.info("Upstream is cancelled or complete. Not requesting another link.");
return;
}
synchronized (lock) {
if (currentLink != null) {
logger.info("Current link exists. Not requesting another link.");
return;
}
}
logger.info("Requesting a new AmqpReceiveLink from upstream.");
upstream.request(1L);
}
private void onDispose() {
if (retrySubscription != null && !retrySubscription.isDisposed()) {
retrySubscription.dispose();
}
disposeReceiver(currentLink);
currentLink = null;
if (currentLinkSubscriptions != null) {
currentLinkSubscriptions.dispose();
}
}
private void drain() {
if (wip.getAndIncrement() != 0) {
return;
}
int missed = 1;
while (missed != 0) {
drainQueue();
missed = wip.addAndGet(-missed);
}
}
private void drainQueue() {
final CoreSubscriber<? super Message> subscriber = downstream.get();
if (subscriber == null || checkAndSetTerminated()) {
return;
}
long numberRequested = requested;
boolean isEmpty = messageQueue.isEmpty();
while (numberRequested != 0L && !isEmpty) {
if (checkAndSetTerminated()) {
break;
}
long numberEmitted = 0L;
while (numberRequested != numberEmitted) {
if (isEmpty && checkAndSetTerminated()) {
break;
}
final Message message = messageQueue.poll();
if (message == null) {
break;
}
if (isCancelled) {
Operators.onDiscard(message, subscriber.currentContext());
synchronized (queueLock) {
Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null);
pendingMessages.set(0);
}
return;
}
try {
subscriber.onNext(message);
pendingMessages.decrementAndGet();
if (prefetch > 0) {
checkAndAddCredits(currentLink);
}
} catch (Exception e) {
logger.error("Exception occurred while handling downstream onNext operation.", e);
throw logger.logExceptionAsError(Exceptions.propagate(
Operators.onOperatorError(upstream, e, message, subscriber.currentContext())));
}
numberEmitted++;
isEmpty = messageQueue.isEmpty();
}
if (requested != Long.MAX_VALUE) {
numberRequested = REQUESTED.addAndGet(this, -numberEmitted);
}
}
}
private boolean checkAndSetTerminated() {
if (!isTerminated()) {
return false;
}
final CoreSubscriber<? super Message> subscriber = downstream.get();
final Throwable error = lastError;
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onComplete();
}
disposeReceiver(currentLink);
synchronized (queueLock) {
messageQueue.clear();
pendingMessages.set(0);
}
return true;
}
private void checkAndAddCredits(AmqpReceiveLink link) {
if (link == null) {
return;
}
synchronized (lock) {
final int linkCredits = link.getCredits();
final int credits = getCreditsToAdd(linkCredits);
logger.info("Link credits='{}', Link credits to add: '{}'", linkCredits, credits);
if (credits > 0) {
link.addCredits(credits).subscribe();
}
}
}
private int getCreditsToAdd(int linkCredits) {
final CoreSubscriber<? super Message> subscriber = downstream.get();
final long r = requested;
final boolean hasBackpressure = r != Long.MAX_VALUE;
if (subscriber == null || r == 0) {
logger.info("Not adding credits. No downstream subscribers or items requested.");
return 0;
}
final int creditsToAdd;
final int expectedTotalCredit;
if (prefetch == 0) {
if (r <= Integer.MAX_VALUE) {
expectedTotalCredit = (int) r;
} else {
expectedTotalCredit = Integer.MAX_VALUE;
}
} else {
expectedTotalCredit = prefetch;
}
logger.info("linkCredits: '{}', expectedTotalCredit: '{}'", linkCredits, expectedTotalCredit);
synchronized (queueLock) {
final int queuedMessages = pendingMessages.get();
final int pending = queuedMessages + linkCredits;
if (hasBackpressure) {
creditsToAdd = Math.max(expectedTotalCredit - pending, 0);
} else {
creditsToAdd = minimumNumberOfMessages >= queuedMessages
? Math.max(expectedTotalCredit - pending, 0)
: 0;
}
logger.info("prefetch: '{}', requested: '{}', linkCredits: '{}', expectedTotalCredit: '{}', queuedMessages:"
+ "'{}', creditsToAdd: '{}', messageQueue.size(): '{}'", getPrefetch(), r, linkCredits,
expectedTotalCredit, queuedMessages, creditsToAdd, messageQueue.size());
}
return creditsToAdd;
}
private void disposeReceiver(AmqpReceiveLink link) {
if (link == null) {
return;
}
try {
if (link instanceof AsyncCloseable) {
((AsyncCloseable) link).closeAsync().subscribe();
} else {
link.dispose();
}
} catch (Exception error) {
logger.warning("linkName[{}] entityPath[{}] Unable to dispose of link.", link.getLinkName(),
link.getEntityPath(), error);
}
}
} |
Fixed | public void createItem_withBulk() throws InterruptedException {
int totalRequest = getTotalRequest(180, 200);
PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition();
pkDefinition.setPaths(Collections.singletonList("/mypk"));
CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection(
this.bulkClient,
bulkAsyncContainer.getDatabase().getId(),
new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition));
ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder()
.setGroupName("test-group")
.setTargetThroughputThreshold(0.2)
.setDefault(true)
.build();
bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig);
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge(
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey);
return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey));
}),
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey);
return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey));
}));
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
try {
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
Thread.sleep(1000);
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 2);
} finally {
bulkAsyncContainerWithThroughputControl.delete().block();
}
} | ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() | public void createItem_withBulk() {
int totalRequest = getTotalRequest();
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge(
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey);
return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey));
}),
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey);
return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey));
}));
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 2);
} | class CosmosBulkAsyncTest extends BatchTestBase {
private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class);
private CosmosAsyncClient bulkClient;
private CosmosAsyncContainer bulkAsyncContainer;
@Factory(dataProvider = "clientBuildersWithDirectSession")
public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) {
super(clientBuilder);
}
@BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT)
public void before_CosmosBulkAsyncTest() {
assertThat(this.bulkClient).isNull();
ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions()
.setMaxRetryAttemptsOnThrottledRequests(1000000)
.setMaxRetryWaitTime(Duration.ofDays(1));
this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient();
bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient);
}
@AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
public void afterClass() {
safeCloseAsync(this.bulkClient);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void createItemMultipleTimesWithOperationOnFly_withBulk() {
int totalRequest = getTotalRequest();
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge(
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey);
return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey));
}),
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey);
return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey));
}));
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
HashSet<Object> distinctDocs = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
Object testDoc = cosmosBulkItemResponse.getItem(Object.class);
distinctDocs.add(testDoc);
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 2);
assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
Object testDoc = cosmosBulkItemResponse.getItem(Object.class);
distinctDocs.add(testDoc);
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 4);
assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void runCreateItemMultipleTimesWithFixedOperations_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
}
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
HashSet<Object> distinctDocs = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer
.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions);
createResponseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
distinctDocs.add(testDoc);
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkOperationResponse);
})
.blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
createResponseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkOperationResponse);
})
.blockLast();
assertThat(processedDoc.get()).isEqualTo(2 * totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void createItemWithError_withBulk() {
int totalRequest = getTotalRequest();
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
if (i == 20 || i == 40 || i == 60) {
return Mono.error(new Exception("ex"));
}
return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
});
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(15);
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
AtomicInteger processedDoc = new AtomicInteger(0);
AtomicInteger erroredDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if(cosmosBulkItemResponse == null) {
erroredDoc.incrementAndGet();
return Mono.empty();
} else {
processedDoc.incrementAndGet();
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}
}).blockLast();
assertThat(erroredDoc.get()).isEqualTo(0);
assertThat(processedDoc.get()).isEqualTo(totalRequest - 3);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void upsertItem_withbulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)));
}
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(2);
Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer
.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions);
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost()));
assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem());
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void deleteItem_withBulk() {
int totalRequest = Math.min(getTotalRequest(), 20);
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> deleteCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue());
});
BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(1);
AtomicInteger processedDoc = new AtomicInteger(0);
bulkAsyncContainer
.processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions)
.flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void readItem_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> readCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue());
});
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
AtomicInteger processedDoc = new AtomicInteger(0);
bulkAsyncContainer
.processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions)
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void readItemMultipleTimes_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> readCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue());
});
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
HashSet<TestDoc> distinctDocs = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer
.processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions)
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
distinctDocs.add(testDoc);
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkOperationResponse);
});
readResponseFlux
.blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
readResponseFlux
.blockLast();
assertThat(processedDoc.get()).isEqualTo(2 * totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void replaceItem_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> replaceCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getReplaceItemOperation(
testDoc.getId(),
cosmosItemOperation.getItem(),
cosmosItemOperation.getPartitionKeyValue());
});
AtomicInteger processedDoc = new AtomicInteger(0);
bulkAsyncContainer
.processBulkOperations(replaceCosmosItemOperationFlux)
.flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem());
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) {
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer
.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions);
HashSet<Integer> distinctIndex = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
createResonseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
distinctIndex.add(testDoc.getCost());
assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost()));
assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem());
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size());
assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size());
}
private int getTotalRequest(int min, int max) {
int countRequest = new Random().nextInt(max - min) + min;
logger.info("Total count of request for this test case: " + countRequest);
return countRequest;
}
private int getTotalRequest() {
return getTotalRequest(200, 300);
}
} | class CosmosBulkAsyncTest extends BatchTestBase {
private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class);
private CosmosAsyncClient bulkClient;
private CosmosAsyncContainer bulkAsyncContainer;
@Factory(dataProvider = "clientBuildersWithDirectSession")
public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) {
super(clientBuilder);
}
@BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT)
public void before_CosmosBulkAsyncTest() {
assertThat(this.bulkClient).isNull();
ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions()
.setMaxRetryAttemptsOnThrottledRequests(1000000)
.setMaxRetryWaitTime(Duration.ofDays(1));
this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient();
bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient);
}
@AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
public void afterClass() {
safeCloseAsync(this.bulkClient);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void createItem_withBulkAndThroughputControl() throws InterruptedException {
int totalRequest = getTotalRequest(180, 200);
PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition();
pkDefinition.setPaths(Collections.singletonList("/mypk"));
CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection(
this.bulkClient,
bulkAsyncContainer.getDatabase().getId(),
new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition));
ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder()
.setGroupName("test-group")
.setTargetThroughputThreshold(0.2)
.setDefault(true)
.build();
bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig);
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge(
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey);
return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey));
}),
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey);
return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey));
}));
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
try {
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
Thread.sleep(1000);
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 2);
} finally {
bulkAsyncContainerWithThroughputControl.delete().block();
}
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void createItemMultipleTimesWithOperationOnFly_withBulk() {
int totalRequest = getTotalRequest();
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge(
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey);
return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey));
}),
Flux.range(0, totalRequest).map(i -> {
String partitionKey = UUID.randomUUID().toString();
EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey);
return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey));
}));
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
HashSet<Object> distinctDocs = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
Object testDoc = cosmosBulkItemResponse.getItem(Object.class);
distinctDocs.add(testDoc);
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 2);
assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
Object testDoc = cosmosBulkItemResponse.getItem(Object.class);
distinctDocs.add(testDoc);
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest * 4);
assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void runCreateItemMultipleTimesWithFixedOperations_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
}
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
HashSet<Object> distinctDocs = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer
.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions);
createResponseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
distinctDocs.add(testDoc);
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkOperationResponse);
})
.blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
createResponseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkOperationResponse);
})
.blockLast();
assertThat(processedDoc.get()).isEqualTo(2 * totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void createItemWithError_withBulk() {
int totalRequest = getTotalRequest();
Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
if (i == 20 || i == 40 || i == 60) {
return Mono.error(new Exception("ex"));
}
return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
});
BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(15);
Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer
.processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions);
AtomicInteger processedDoc = new AtomicInteger(0);
AtomicInteger erroredDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> {
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if(cosmosBulkItemResponse == null) {
erroredDoc.incrementAndGet();
return Mono.empty();
} else {
processedDoc.incrementAndGet();
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}
}).blockLast();
assertThat(erroredDoc.get()).isEqualTo(0);
assertThat(processedDoc.get()).isEqualTo(totalRequest - 3);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void upsertItem_withbulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)));
}
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(2);
Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer
.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions);
AtomicInteger processedDoc = new AtomicInteger(0);
responseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost()));
assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem());
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void deleteItem_withBulk() {
int totalRequest = Math.min(getTotalRequest(), 20);
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> deleteCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue());
});
BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>();
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(1);
AtomicInteger processedDoc = new AtomicInteger(0);
bulkAsyncContainer
.processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions)
.flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void readItem_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> readCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue());
});
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
AtomicInteger processedDoc = new AtomicInteger(0);
bulkAsyncContainer
.processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions)
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void readItemMultipleTimes_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> readCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue());
});
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(30);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
HashSet<TestDoc> distinctDocs = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer
.processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions)
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
distinctDocs.add(testDoc);
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkOperationResponse);
});
readResponseFlux
.blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
readResponseFlux
.blockLast();
assertThat(processedDoc.get()).isEqualTo(2 * totalRequest);
assertThat(distinctDocs.size()).isEqualTo(totalRequest);
}
@Test(groups = {"simple"}, timeOut = TIMEOUT)
public void replaceItem_withBulk() {
int totalRequest = getTotalRequest();
List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>();
for (int i = 0; i < totalRequest; i++) {
String partitionKey = UUID.randomUUID().toString();
TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20);
cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)));
}
createItemsAndVerify(cosmosItemOperations);
Flux<CosmosItemOperation> replaceCosmosItemOperationFlux =
Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> {
TestDoc testDoc = cosmosItemOperation.getItem();
return BulkOperations.getReplaceItemOperation(
testDoc.getId(),
cosmosItemOperation.getItem(),
cosmosItemOperation.getPartitionKeyValue());
});
AtomicInteger processedDoc = new AtomicInteger(0);
bulkAsyncContainer
.processBulkOperations(replaceCosmosItemOperationFlux)
.flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem());
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(totalRequest);
}
private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) {
BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(100);
bulkProcessingOptions.setMaxMicroBatchConcurrency(5);
Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer
.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions);
HashSet<Integer> distinctIndex = new HashSet<>();
AtomicInteger processedDoc = new AtomicInteger(0);
createResonseFlux
.flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> {
processedDoc.incrementAndGet();
CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse();
if (cosmosBulkOperationResponse.getException() != null) {
logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException());
fail(cosmosBulkOperationResponse.getException().toString());
}
assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code());
assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0);
assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull();
assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull();
assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull();
assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull();
TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class);
distinctIndex.add(testDoc.getCost());
assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost()));
assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem());
assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem());
return Mono.just(cosmosBulkItemResponse);
}).blockLast();
assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size());
assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size());
}
private int getTotalRequest(int min, int max) {
int countRequest = new Random().nextInt(max - min) + min;
logger.info("Total count of request for this test case: " + countRequest);
return countRequest;
}
private int getTotalRequest() {
return getTotalRequest(200, 300);
}
} |
We still call next.process() in the else block, so the rest of the pipeline shouldn't get skipped. I can refactor it as suggested. | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
HttpHeaders requestHeaders = context.getHttpRequest().getHeaders();
String initialRangeHeader = requestHeaders.getValue(RANGE_HEADER);
if (initialRangeHeader == null) {
return next.process().flatMap(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody() != null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
/*
* Deserialize encryption data.
* If there is no encryption data set on the blob, then we can return the request as is since we
* didn't expand the range at all.
*/
EncryptionData encryptionData = EncryptionData.getAndValidateEncryptionData(
httpResponse.getHeaderValue(Constants.HeaderConstants.X_MS_META + "-"
+ ENCRYPTION_DATA_KEY), requiresEncryption);
if (encryptionData == null) {
return Mono.just(httpResponse);
}
/*
* We will need to know the total size of the data to know when to finalize the decryption. If it
* was not set originally with the intent of downloading the whole blob, update it here.
* If there was no range set on the request, we skipped instantiating a BlobRange as we did not have
* encryption data at the time. Instantiate now with a BlobRange that indicates a full blob.
*/
EncryptedBlobRange encryptedRange = new EncryptedBlobRange(new BlobRange(0), encryptionData);
encryptedRange.setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the encryption
* block size. Padding is only ever present in track 1.
*/
boolean padding = encryptionData.getEncryptionAgent().getProtocol().equals(ENCRYPTION_PROTOCOL_V1)
&& (encryptedRange.toBlobRange().getOffset()
+ encryptedRange.toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(), encryptedRange, padding,
encryptionData, httpResponse.getRequest().getUrl().toString());
return Mono.just(new BlobDecryptionPolicy.DecryptedResponse(httpResponse, plainTextData));
} else {
return Mono.just(httpResponse);
}
});
} else {
BlobRequestConditions rc = extractRequestConditionsFromRequest(requestHeaders);
return this.blobClient.getPropertiesWithResponse(rc).flatMap(response -> {
EncryptionData data = EncryptionData.getAndValidateEncryptionData(
response.getValue().getMetadata().get(CryptographyConstants.ENCRYPTION_DATA_KEY),
requiresEncryption);
return data == null ? next.process() : Mono.just(data)
.flatMap(encryptionData -> {
EncryptedBlobRange encryptedRange = EncryptedBlobRange.getEncryptedBlobRangeFromHeader(
initialRangeHeader, encryptionData);
if (context.getHttpRequest().getHeaders().getValue(RANGE_HEADER) != null
&& encryptionData != null) {
requestHeaders.set(RANGE_HEADER, encryptedRange.toBlobRange().toString());
}
return Mono.zip(Mono.just(encryptionData), Mono.just(encryptedRange));
})
.flatMap(tuple2 -> next.process().flatMap(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody()
!= null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
if (httpResponse.getHeaderValue(Constants.HeaderConstants.X_MS_META + "-"
+ ENCRYPTION_DATA_KEY) == null) {
return Mono.just(httpResponse);
}
tuple2.getT2().setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the
* encryption block size. Padding is only ever present in track 1.
*/
boolean padding = tuple2.getT1().getEncryptionAgent().getProtocol()
.equals(ENCRYPTION_PROTOCOL_V1)
&& (tuple2.getT2().toBlobRange().getOffset() + tuple2.getT2().toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(), tuple2.getT2(), padding,
tuple2.getT1(), httpResponse.getRequest().getUrl().toString());
return Mono.just(new DecryptedResponse(httpResponse, plainTextData));
} else {
return Mono.just(httpResponse);
}
}));
});
}
} | return data == null ? next.process() : Mono.just(data) | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
HttpHeaders requestHeaders = context.getHttpRequest().getHeaders();
String initialRangeHeader = requestHeaders.getValue(RANGE_HEADER);
if (initialRangeHeader == null) {
return next.process().flatMap(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody() != null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
/*
* Deserialize encryption data.
* If there is no encryption data set on the blob, then we can return the request as is since we
* didn't expand the range at all.
*/
EncryptionData encryptionData = EncryptionData.getAndValidateEncryptionData(
httpResponse.getHeaderValue(Constants.HeaderConstants.X_MS_META + "-"
+ ENCRYPTION_DATA_KEY), requiresEncryption);
if (encryptionData == null) {
return Mono.just(httpResponse);
}
/*
* We will need to know the total size of the data to know when to finalize the decryption. If it
* was not set originally with the intent of downloading the whole blob, update it here.
* If there was no range set on the request, we skipped instantiating a BlobRange as we did not have
* encryption data at the time. Instantiate now with a BlobRange that indicates a full blob.
*/
EncryptedBlobRange encryptedRange = new EncryptedBlobRange(new BlobRange(0), encryptionData);
encryptedRange.setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the encryption
* block size. Padding is only ever present in track 1.
*/
boolean padding = encryptionData.getEncryptionAgent().getProtocol().equals(ENCRYPTION_PROTOCOL_V1)
&& (encryptedRange.toBlobRange().getOffset()
+ encryptedRange.toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(), encryptedRange, padding,
encryptionData, httpResponse.getRequest().getUrl().toString());
return Mono.just(new BlobDecryptionPolicy.DecryptedResponse(httpResponse, plainTextData));
} else {
return Mono.just(httpResponse);
}
});
} else {
BlobRequestConditions rc = extractRequestConditionsFromRequest(requestHeaders);
return this.blobClient.getPropertiesWithResponse(rc).flatMap(response -> {
EncryptionData encryptionData = EncryptionData.getAndValidateEncryptionData(
response.getValue().getMetadata().get(CryptographyConstants.ENCRYPTION_DATA_KEY),
requiresEncryption);
String etag = response.getValue().getETag();
requestHeaders.set("ETag", etag);
if (encryptionData == null) {
return next.process();
}
EncryptedBlobRange encryptedRange = EncryptedBlobRange.getEncryptedBlobRangeFromHeader(
initialRangeHeader, encryptionData);
if (context.getHttpRequest().getHeaders().getValue(RANGE_HEADER) != null) {
requestHeaders.set(RANGE_HEADER, encryptedRange.toBlobRange().toString());
}
return next.process().map(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody()
!= null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
if (httpResponse.getHeaderValue(ENCRYPTION_METADATA_HEADER) == null) {
return httpResponse;
}
encryptedRange.setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the
* encryption block size. Padding is only ever present in track 1.
*/
boolean padding = encryptionData.getEncryptionAgent().getProtocol()
.equals(ENCRYPTION_PROTOCOL_V1)
&& (encryptedRange.toBlobRange().getOffset() + encryptedRange.toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(),
encryptedRange, padding, encryptionData,
httpResponse.getRequest().getUrl().toString());
return new DecryptedResponse(httpResponse, plainTextData);
} else {
return httpResponse;
}
});
});
}
} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} |
Refactored to remove a bunch of async calls | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
HttpHeaders requestHeaders = context.getHttpRequest().getHeaders();
String initialRangeHeader = requestHeaders.getValue(RANGE_HEADER);
if (initialRangeHeader == null) {
return next.process().flatMap(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody() != null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
/*
* Deserialize encryption data.
* If there is no encryption data set on the blob, then we can return the request as is since we
* didn't expand the range at all.
*/
EncryptionData encryptionData = EncryptionData.getAndValidateEncryptionData(
httpResponse.getHeaderValue(Constants.HeaderConstants.X_MS_META + "-"
+ ENCRYPTION_DATA_KEY), requiresEncryption);
if (encryptionData == null) {
return Mono.just(httpResponse);
}
/*
* We will need to know the total size of the data to know when to finalize the decryption. If it
* was not set originally with the intent of downloading the whole blob, update it here.
* If there was no range set on the request, we skipped instantiating a BlobRange as we did not have
* encryption data at the time. Instantiate now with a BlobRange that indicates a full blob.
*/
EncryptedBlobRange encryptedRange = new EncryptedBlobRange(new BlobRange(0), encryptionData);
encryptedRange.setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the encryption
* block size. Padding is only ever present in track 1.
*/
boolean padding = encryptionData.getEncryptionAgent().getProtocol().equals(ENCRYPTION_PROTOCOL_V1)
&& (encryptedRange.toBlobRange().getOffset()
+ encryptedRange.toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(), encryptedRange, padding,
encryptionData, httpResponse.getRequest().getUrl().toString());
return Mono.just(new BlobDecryptionPolicy.DecryptedResponse(httpResponse, plainTextData));
} else {
return Mono.just(httpResponse);
}
});
} else {
BlobRequestConditions rc = extractRequestConditionsFromRequest(requestHeaders);
return this.blobClient.getPropertiesWithResponse(rc).flatMap(response -> {
EncryptionData data = EncryptionData.getAndValidateEncryptionData(
response.getValue().getMetadata().get(CryptographyConstants.ENCRYPTION_DATA_KEY),
requiresEncryption);
return data == null ? next.process() : Mono.just(data)
.flatMap(encryptionData -> {
EncryptedBlobRange encryptedRange = EncryptedBlobRange.getEncryptedBlobRangeFromHeader(
initialRangeHeader, encryptionData);
if (context.getHttpRequest().getHeaders().getValue(RANGE_HEADER) != null
&& encryptionData != null) {
requestHeaders.set(RANGE_HEADER, encryptedRange.toBlobRange().toString());
}
return Mono.zip(Mono.just(encryptionData), Mono.just(encryptedRange));
})
.flatMap(tuple2 -> next.process().flatMap(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody()
!= null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
if (httpResponse.getHeaderValue(Constants.HeaderConstants.X_MS_META + "-"
+ ENCRYPTION_DATA_KEY) == null) {
return Mono.just(httpResponse);
}
tuple2.getT2().setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the
* encryption block size. Padding is only ever present in track 1.
*/
boolean padding = tuple2.getT1().getEncryptionAgent().getProtocol()
.equals(ENCRYPTION_PROTOCOL_V1)
&& (tuple2.getT2().toBlobRange().getOffset() + tuple2.getT2().toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(), tuple2.getT2(), padding,
tuple2.getT1(), httpResponse.getRequest().getUrl().toString());
return Mono.just(new DecryptedResponse(httpResponse, plainTextData));
} else {
return Mono.just(httpResponse);
}
}));
});
}
} | } | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
HttpHeaders requestHeaders = context.getHttpRequest().getHeaders();
String initialRangeHeader = requestHeaders.getValue(RANGE_HEADER);
if (initialRangeHeader == null) {
return next.process().flatMap(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody() != null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
/*
* Deserialize encryption data.
* If there is no encryption data set on the blob, then we can return the request as is since we
* didn't expand the range at all.
*/
EncryptionData encryptionData = EncryptionData.getAndValidateEncryptionData(
httpResponse.getHeaderValue(Constants.HeaderConstants.X_MS_META + "-"
+ ENCRYPTION_DATA_KEY), requiresEncryption);
if (encryptionData == null) {
return Mono.just(httpResponse);
}
/*
* We will need to know the total size of the data to know when to finalize the decryption. If it
* was not set originally with the intent of downloading the whole blob, update it here.
* If there was no range set on the request, we skipped instantiating a BlobRange as we did not have
* encryption data at the time. Instantiate now with a BlobRange that indicates a full blob.
*/
EncryptedBlobRange encryptedRange = new EncryptedBlobRange(new BlobRange(0), encryptionData);
encryptedRange.setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the encryption
* block size. Padding is only ever present in track 1.
*/
boolean padding = encryptionData.getEncryptionAgent().getProtocol().equals(ENCRYPTION_PROTOCOL_V1)
&& (encryptedRange.toBlobRange().getOffset()
+ encryptedRange.toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(), encryptedRange, padding,
encryptionData, httpResponse.getRequest().getUrl().toString());
return Mono.just(new BlobDecryptionPolicy.DecryptedResponse(httpResponse, plainTextData));
} else {
return Mono.just(httpResponse);
}
});
} else {
BlobRequestConditions rc = extractRequestConditionsFromRequest(requestHeaders);
return this.blobClient.getPropertiesWithResponse(rc).flatMap(response -> {
EncryptionData encryptionData = EncryptionData.getAndValidateEncryptionData(
response.getValue().getMetadata().get(CryptographyConstants.ENCRYPTION_DATA_KEY),
requiresEncryption);
String etag = response.getValue().getETag();
requestHeaders.set("ETag", etag);
if (encryptionData == null) {
return next.process();
}
EncryptedBlobRange encryptedRange = EncryptedBlobRange.getEncryptedBlobRangeFromHeader(
initialRangeHeader, encryptionData);
if (context.getHttpRequest().getHeaders().getValue(RANGE_HEADER) != null) {
requestHeaders.set(RANGE_HEADER, encryptedRange.toBlobRange().toString());
}
return next.process().map(httpResponse -> {
if (httpResponse.getRequest().getHttpMethod() == HttpMethod.GET && httpResponse.getBody()
!= null) {
HttpHeaders responseHeaders = httpResponse.getHeaders();
if (httpResponse.getHeaderValue(ENCRYPTION_METADATA_HEADER) == null) {
return httpResponse;
}
encryptedRange.setAdjustedDownloadCount(
Long.parseLong(responseHeaders.getValue(CONTENT_LENGTH)));
/*
* We expect padding only if we are at the end of a blob and it is not a multiple of the
* encryption block size. Padding is only ever present in track 1.
*/
boolean padding = encryptionData.getEncryptionAgent().getProtocol()
.equals(ENCRYPTION_PROTOCOL_V1)
&& (encryptedRange.toBlobRange().getOffset() + encryptedRange.toBlobRange().getCount()
> (blobSize(responseHeaders) - ENCRYPTION_BLOCK_SIZE));
Flux<ByteBuffer> plainTextData = this.decryptBlob(httpResponse.getBody(),
encryptedRange, padding, encryptionData,
httpResponse.getRequest().getUrl().toString());
return new DecryptedResponse(httpResponse, plainTextData);
} else {
return httpResponse;
}
});
});
}
} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} | class with the specified key and resolver.
* <p>
* If the generated policy is intended to be used for encryption, users are expected to provide a key at the
* minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is
* intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key
* resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on
* the key and use it.
*
* @param key An object of type {@link AsyncKeyEncryptionKey} |
nit: don't need to specify `this` | public String getCallConnectionId() {
return this.callConnectionAsync.getCallConnectionId();
} | return this.callConnectionAsync.getCallConnectionId(); | public String getCallConnectionId() {
return callConnectionAsync.getCallConnectionId();
} | class CallConnection {
private final CallConnectionAsync callConnectionAsync;
private final ClientLogger logger = new ClientLogger(CallConnection.class);
CallConnection(CallConnectionAsync callConnectionAsync) {
this.callConnectionAsync = callConnectionAsync;
}
/**
* Get the call connection id property
*
* @return the id value.
*/
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param loop The flag indicating whether audio file needs to be played in loop or not.
* @param audioFileId An id for the media in the AudioFileUri, using which we cache the media.
* @param callbackUri call back uri to receive notifications.
* @param operationContext The value to identify context of the operation.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PlayAudioResult playAudio(String audioFileUri,
boolean loop,
String audioFileId,
String callbackUri,
String operationContext) {
PlayAudioRequest playAudioRequest = new PlayAudioRequest();
playAudioRequest.setAudioFileUri(audioFileUri);
playAudioRequest.setLoop(loop);
playAudioRequest.setAudioFileId(audioFileId);
playAudioRequest.setOperationContext(operationContext);
playAudioRequest.setCallbackUri(callbackUri);
return callConnectionAsync.playAudio(playAudioRequest).block();
}
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param loop The flag indicating whether audio file needs to be played in loop or not.
* @param audioFileId An id for the media in the AudioFileUri, using which we cache the media.
* @param callbackUri call back uri to receive notifications.
* @param operationContext The value to identify context of the operation.
* @param context A {@link Context} representing the request context.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<PlayAudioResult> playAudioWithResponse(String audioFileUri,
boolean loop,
String audioFileId,
String callbackUri,
String operationContext,
Context context) {
PlayAudioRequest playAudioRequest = new PlayAudioRequest();
playAudioRequest.setAudioFileUri(audioFileUri);
playAudioRequest.setLoop(loop);
playAudioRequest.setAudioFileId(audioFileId);
playAudioRequest.setOperationContext(operationContext);
playAudioRequest.setCallbackUri(callbackUri);
return callConnectionAsync.playAudioWithResponse(playAudioRequest, context).block();
}
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param playAudioOptions Options for play audio.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PlayAudioResult playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) {
PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions);
return callConnectionAsync.playAudio(playAudioRequest).block();
}
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param playAudioOptions Options for play audio.
* @param context A {@link Context} representing the request context.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<PlayAudioResult> playAudioWithResponse(String audioFileUri,
PlayAudioOptions playAudioOptions,
Context context) {
PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions);
return callConnectionAsync.playAudioWithResponse(playAudioRequest, context).block();
}
/**
* Disconnect the current caller in a Group-call or end a p2p-call.
*
* @return response for a successful Hangup request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Void hangup() {
return callConnectionAsync.hangup().block();
}
/**
* Disconnect the current caller in a Group-call or end a p2p-call.
*
* @param context A {@link Context} representing the request context.
* @return response for a successful HangupCall request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> hangupWithResponse(Context context) {
return callConnectionAsync.hangupWithResponse(context).block();
}
/**
* Cancel all media operations in the call.
*
* @param operationContext operationContext.
* @return response for a successful CancelMediaOperations request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public CancelAllMediaOperationsResult cancelAllMediaOperations(String operationContext) {
return callConnectionAsync.cancelAllMediaOperations(operationContext).block();
}
/**
* Cancel all media operations in the call.
*
* @param operationContext operationContext.
* @param context A {@link Context} representing the request context.
* @return response for a successful CancelMediaOperations request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<CancelAllMediaOperationsResult> cancelAllMediaOperationsWithResponse(String operationContext,
Context context) {
return callConnectionAsync.cancelAllMediaOperationsWithResponse(operationContext, context).block();
}
/**
* Add a participant to the call.
*
* @param participant Invited participant.
* @param alternateCallerId The phone number to use when adding a phone number participant.
* @param operationContext operationContext.
* @return response for a successful addParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Void addParticipant(CommunicationIdentifier participant,
String alternateCallerId,
String operationContext) {
return callConnectionAsync.addParticipant(participant, alternateCallerId, operationContext).block();
}
/**
* Add a participant to the call.
*
* @param participant Invited participant.
* @param alternateCallerId The phone number to use when adding a phone number participant.
* @param operationContext operationContext.
* @param context A {@link Context} representing the request context.
* @return response for a successful addParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> addParticipantWithResponse(CommunicationIdentifier participant,
String alternateCallerId,
String operationContext,
Context context) {
return callConnectionAsync
.addParticipantWithResponse(participant, alternateCallerId, operationContext, context).block();
}
/**
* Remove a participant from the call.
*
* @param participantId Participant id.
* @return response for a successful removeParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Void removeParticipant(String participantId) {
return callConnectionAsync.removeParticipant(participantId).block();
}
/**
* Remove a participant from the call.
*
* @param participantId Participant id.
* @param context A {@link Context} representing the request context.
* @return response for a successful removeParticipant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> removeParticipantWithResponse(String participantId, Context context) {
return callConnectionAsync.removeParticipantWithResponse(participantId, context).block();
}
} | class CallConnection {
private final CallConnectionAsync callConnectionAsync;
private final ClientLogger logger = new ClientLogger(CallConnection.class);
CallConnection(CallConnectionAsync callConnectionAsync) {
this.callConnectionAsync = callConnectionAsync;
}
/**
* Get the call connection id property
*
* @return the id value.
*/
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param loop The flag indicating whether audio file needs to be played in loop or not.
* @param audioFileId An id for the media in the AudioFileUri, using which we cache the media.
* @param callbackUri call back uri to receive notifications.
* @param operationContext The value to identify context of the operation. This is used to co-relate other
* communications related to this operation
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PlayAudioResult playAudio(
String audioFileUri,
boolean loop,
String audioFileId,
String callbackUri,
String operationContext) {
return callConnectionAsync
.playAudioInternal(audioFileUri, loop, audioFileId, callbackUri, operationContext).block();
}
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param playAudioOptions Options for play audio.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PlayAudioResult playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) {
return callConnectionAsync.playAudioInternal(audioFileUri, playAudioOptions).block();
}
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param loop The flag indicating whether audio file needs to be played in loop or not.
* @param audioFileId An id for the media in the AudioFileUri, using which we cache the media.
* @param callbackUri call back uri to receive notifications.
* @param operationContext The value to identify context of the operation. This is used to co-relate other
* communications related to this operation
* @param context A {@link Context} representing the request context.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<PlayAudioResult> playAudioWithResponse(
String audioFileUri,
boolean loop,
String audioFileId,
String callbackUri,
String operationContext,
Context context) {
return callConnectionAsync
.playAudioWithResponseInternal(
audioFileUri,
loop,
audioFileId,
callbackUri,
operationContext,
context)
.block();
}
/**
* Play audio in a call.
*
* @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format
* audio prompts are supported. More specifically, the audio content in the wave file must
* be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate.
* @param playAudioOptions Options for play audio.
* @param context A {@link Context} representing the request context.
* @return the response payload for play audio operation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<PlayAudioResult> playAudioWithResponse(
String audioFileUri,
PlayAudioOptions playAudioOptions,
Context context) {
return callConnectionAsync
.playAudioWithResponseInternal(audioFileUri, playAudioOptions, context)
.block();
}
/**
* Disconnect the current caller in a group-call or end a p2p-call.
*
* @return response for a successful hangup request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Void hangup() {
return callConnectionAsync.hangup().block();
}
/**
* Disconnect the current caller in a group-call or end a p2p-call.
*
* @param context A {@link Context} representing the request context.
* @return response for a successful hangup request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> hangupWithResponse(Context context) {
return callConnectionAsync.hangupWithResponse(context).block();
}
/**
* Cancel all media operations in the call.
*
* @param operationContext The value to identify context of the operation. This is used to co-relate other
* communications related to this operation
* @return response for a successful cancel all media operations request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public CancelAllMediaOperationsResult cancelAllMediaOperations(String operationContext) {
return callConnectionAsync.cancelAllMediaOperations(operationContext).block();
}
/**
* Cancel all media operations in the call.
*
* @param operationContext The value to identify context of the operation. This is used to co-relate other
* communications related to this operation
* @param context A {@link Context} representing the request context.
* @return response for a successful cancel all media operations request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<CancelAllMediaOperationsResult> cancelAllMediaOperationsWithResponse(
String operationContext,
Context context) {
return callConnectionAsync.cancelAllMediaOperationsWithResponse(operationContext, context).block();
}
/**
* Add a participant to the call.
*
* @param participant Invited participant.
* @param alternateCallerId The phone number to use when adding a phone number participant.
* @param operationContext The value to identify context of the operation. This is used to co-relate other
* communications related to this operation
* @return response for a successful add participant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Void addParticipant(
CommunicationIdentifier participant,
String alternateCallerId,
String operationContext) {
return callConnectionAsync.addParticipant(participant, alternateCallerId, operationContext).block();
}
/**
* Add a participant to the call.
*
* @param participant Invited participant.
* @param alternateCallerId The phone number to use when adding a phone number participant.
* @param operationContext The value to identify context of the operation. This is used to co-relate other
* communications related to this operation
* @param context A {@link Context} representing the request context.
* @return response for a successful add participant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> addParticipantWithResponse(
CommunicationIdentifier participant,
String alternateCallerId,
String operationContext,
Context context) {
return callConnectionAsync
.addParticipantWithResponse(participant, alternateCallerId, operationContext, context).block();
}
/**
* Remove a participant from the call.
*
* @param participantId Participant id.
* @return response for a successful remove participant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Void removeParticipant(String participantId) {
return callConnectionAsync.removeParticipant(participantId).block();
}
/**
* Remove a participant from the call.
*
* @param participantId Participant id.
* @param context A {@link Context} representing the request context.
* @return response for a successful remove participant request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> removeParticipantWithResponse(String participantId, Context context) {
return callConnectionAsync.removeParticipantWithResponse(participantId, context).block();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.